使用alarmManager和服务只在特定的时间段执行进度的通知只在、时间段、进度、和服务

2023-09-05 07:54:02 作者:し蔓珠唦譁の霺笶︶

我要建一个应用程序,将在用户醒着的时候触发,在特定的时间间隔通知。

我有一个alarmManager运行的服务里面。该服务是通过按一下按钮明确地开始对主要活动,并具有在特定的时间invervals的alarmManager执行通知。我怎么会去在特定的时间为一天停止通知?我不希望这些通知被解雇,例如,当用户在睡觉。

我的code当前烧制通知在用户设定的时间间隔低于(进口删除....这是够长的话):

 公共类FartSmackinChunks延伸服务{
    公示scheduleNotification;
    公共AlarmManager alarmScheduleManager;
    公共PendingIntent alarmScheduleIntent;
    私人布尔autoUpdateBoolean =真;
    私人诠释intervalsGoneByInt = 0;
    私人的通知的通知;
    公共静态最终诠释NOTIFICATION_ID = 1;

    @覆盖
    公共无效的onCreate(){
        // TODO:在创建服务时要执行的操作。
        INT图标= R.drawable.icon;
        字符串tickerText =间隔炒鱿鱼;
        时长= System.currentTimeMillis的();
        scheduleNotification =新的通知(图标,tickerText时);

        alarmScheduleManager =(AlarmManager)getSystemService(Context.ALARM_SERVICE);

        字符串ALARM_ACTION;
        ALARM_ACTION = ScheduleAlarmReceiver.ACTION_REFRESH_SCHEDULE_ALARM;
        意图int​​entToFire =新的意图(ALARM_ACTION);
        alarmScheduleIntent = PendingIntent.getBroadcast(此,0,intentToFire,
        0);
    }

    @覆盖
    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
        共享preferences myShared preferences =
        preferenceManager.getDefaultShared preferences(getApplicationContext());
        布尔autoUpdateBoolean =
        myShared preferences.getBoolean(storedAutoUpdateBoolean,假);
        字符串updateFreq =
        myShared preferences.getString(storedInitialAverageTimeInterval,00:00:00);

        SimpleDateFormat的dfInterval =新的SimpleDateFormat(HH:MM:SS);

        日期intervalTimeAsDateObject = NULL;
        长updateFreqMilliLong;
        尝试 {
            intervalTimeAsDateObject = dfInterval.parse(updateFreq);
        }赶上(ParseException的E){
            e.printStackTrace();
        }

        updateFreqMilliLong = intervalTimeAsDateObject.getTime() -  18000000;

        如果(autoUpdateBoolean){
            INT alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
            长timetoRefresh = SystemClock.elapsedRealtime()+
            updateFreqMilliLong;
            alarmScheduleManager.setInexactRepeating(alarmType,
            timetoRefresh,updateFreqMilliLong,alarmScheduleIntent);
            通知();
        }其他alarmScheduleManager.cancel(alarmScheduleIntent);

        返回Service.START_NOT_STICKY;
    };

    私人无效的通知(){
        **通知东西在这里***
    }

    @覆盖
    公众的IBinder onBind(意向意图){
        // TODO:更换服务绑定实现。
        返回null;
    }

    @覆盖
    公共无效的onDestroy(){
        this.alarmScheduleManager.cancel(alarmScheduleIntent);
    }
}
 

.....我的广播接收器实现此:

 进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.Intent;

公共类ScheduleAlarmReceiver扩展的BroadcastReceiver {

    公共静态最后弦乐ACTION_REFRESH_SCHEDULE_ALARM
    =com.application.ACTION_REFRESH_SCHEDULE_ALARM;

    @覆盖
    公共无效的onReceive(上下文的背景下,意图意图){
        意图startIntent =新的意图(背景下,SmokerReducerService.class);
        context.startService(startIntent);
    }
}
 

我有一点点困难包装我的大脑左右应如何实施。

我在想返工这个code,使得alarmManager射向waketime停在睡眠时间,而所有的服务中是一个计时器,以触发特定的时间间隔通知方法?有没有更好的办法去这样做?

任何投入将是AP preciated。我一直在努力,现在工作了这一点,在我的头上了好几天。

感谢

编辑: @anyone谁遇到这种打算使用一个定时器日常通知:

其运行的服务的内部的定时器将被运行时暂停当设备处于睡眠状态(即...用户将在手机处于待机状态)。为此,使用定时器触发特定的时间间隔通知将无法正常业务范围内开展工作,因为当Android的暂停服务时,它也暂停计时,它抛出了间隔。

AlarmManager研究

要做到这一点,正确的方法是使用AlarmManager待决意图在白天,可以设定闹钟在特定时间的数组。这保证了即使手机放在待机状态,通知(或任何你希望发生的当时)还是会被执行。

解决方案   

我在想返工这个code,使得alarmManager射向waketime停在睡眠时间,而所有的服务中是一个计时器,以触发特定的时间间隔通知方法?有没有更好的办法去这样做?

在我看来,忘记一个'好'的思维方式,它似乎是唯一的出路。用一个定时器控制(启用​​/禁用),另一个计时器是不是太奇怪了,使完整意义上的我。

I'm building an app that will trigger notifications at specific time-intervals during the users waking hours.

I have an alarmManager running inside of a service. The service is explicitly started via button click on the main activity and has the alarmManager executing notifications during specific time invervals. How would I go about stopping the notifications during certain hours of the day? I do not want these notification to be fired, for instance, while the user is sleeping.

My code that is currently firing notifications at user-set intervals is below (imports removed....this is long enough already):

public class FartSmackinChunks extends Service {
    public Notification scheduleNotification;
    public AlarmManager alarmScheduleManager;
    public PendingIntent alarmScheduleIntent;
    private Boolean autoUpdateBoolean = true;
    private int intervalsGoneByInt = 0;
    private Notification notification;
    public static final int NOTIFICATION_ID = 1;

    @Override
    public void onCreate() {
        // TODO: Actions to perform when service is created.
        int icon = R.drawable.icon;
        String tickerText = "INTERVAL FIRED";
        long when = System.currentTimeMillis();
        scheduleNotification = new Notification(icon, tickerText, when);

        alarmScheduleManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

        String ALARM_ACTION;
        ALARM_ACTION = ScheduleAlarmReceiver.ACTION_REFRESH_SCHEDULE_ALARM;
        Intent intentToFire = new Intent(ALARM_ACTION);
        alarmScheduleIntent = PendingIntent.getBroadcast(this, 0, intentToFire,
        0);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        SharedPreferences mySharedPreferences =
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        boolean autoUpdateBoolean =
        mySharedPreferences.getBoolean("storedAutoUpdateBoolean", false);
        String updateFreq =
        mySharedPreferences.getString("storedInitialAverageTimeInterval", "00:00:00");

        SimpleDateFormat dfInterval = new SimpleDateFormat("hh:mm:ss");

        Date intervalTimeAsDateObject = null;
        long updateFreqMilliLong;
        try {
            intervalTimeAsDateObject = dfInterval.parse(updateFreq);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        updateFreqMilliLong = intervalTimeAsDateObject.getTime() - 18000000;

        if (autoUpdateBoolean) {
            int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
            long timetoRefresh = SystemClock.elapsedRealtime() +
            updateFreqMilliLong;
            alarmScheduleManager.setInexactRepeating(alarmType,
            timetoRefresh, updateFreqMilliLong, alarmScheduleIntent);
            notifications();
        } else alarmScheduleManager.cancel(alarmScheduleIntent);

        return Service.START_NOT_STICKY;
    };

    private void notifications() {
        **notification stuff in here***
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Replace with service binding implementation.
        return null;
    }

    @Override
    public void onDestroy() {
        this.alarmScheduleManager.cancel(alarmScheduleIntent);
    }
}

.....and my broadcast receiver implementation here:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class ScheduleAlarmReceiver extends BroadcastReceiver {

    public static final String ACTION_REFRESH_SCHEDULE_ALARM
    = "com.application.ACTION_REFRESH_SCHEDULE_ALARM";

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startIntent = new Intent(context, SmokerReducerService.class);
        context.startService(startIntent);
    }
}

I'm having a little difficulty wrapping my brain around how this should be implemented.

I was thinking to rework this code so that the alarmManager is fired at waketime and stopped at sleepTime, all while inside the service is a Timer that fires the notification method at specific intervals? Is there a better way to go about doing this?

Any input would be appreciated. I've been trying to work this out in my head for days now.

Thanks

EDIT: @anyone who comes across this intending to use a Timer for daily notifications:

A timer which runs inside of a service will be paused by the runtime when the device is put to sleep (ie...the user puts the phone in standby). Therefor, using a Timer to fire notifications at specific time intervals won't work correctly within a service because when Android pauses the service, it also pauses the timer, which throws off the interval.

The correct way to do this is to use AlarmManager with an array of pending intents to set alarms at specific times during the day. This ensures that even if the phone is put in standby, the notifications (or whatever you want to happen at that time) will still be executed.

解决方案

I was thinking to rework this code so that the alarmManager is fired at waketime and stopped at sleepTime, all while inside the service is a Timer that fires the notification method at specific intervals? Is there a better way to go about doing this?

To my mind, forget thinking of a 'better' way, it seems the only way. Using a timer to control (enable/disable) another timer isn't so strange and makes complete sense to me.