使用alarmManager和服务仅在特定时间段执行计划通知

发布于 2024-10-13 08:28:16 字数 3902 浏览 4 评论 0原文

我正在构建一个应用程序,它将在用户醒着的时间内以特定的时间间隔触发通知。

我有一个alarmManager 在服务内运行。该服务通过单击主活动上的按钮显式启动,并让 AlarmManager 在特定时间间隔内执行通知。我该如何在一天中的某些时间停止通知?例如,我不希望在用户睡觉时触发这些通知。

我当前按用户设置的时间间隔触发通知的代码如下(已删除导入......这已经足够长了):

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);
    }
}

.....以及我的广播接收器实现:

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);
    }
}

我在思考时遇到了一些困难围绕如何实施这一点。

我正在考虑修改这段代码,以便alarmManager在唤醒时触发并在睡眠时停止,而服务内部是一个以特定时间间隔触发通知方法的计时器?有更好的方法来做这件事吗?

任何意见将不胜感激。这几天我一直在脑子里想办法解决这个问题。

谢谢

编辑: @任何遇到这种情况打算使用计时器进行每日通知的人:

当设备进入睡眠状态时,在服务内部运行的计时器将被运行时暂停(即......用户将手机放在处于待机状态)。因此,使用计时器以特定时间间隔触发通知将无法在服务中正常工作,因为当 Android 暂停服务时,它也会暂停计时器,从而导致间隔失效。

正确的方法是使用 AlarmManager 和一系列待处理的意图来在一天中的特定时间设置警报。这可以确保即使手机处于待机状态,通知(或您当时想要发生的任何事情)仍然会被执行。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱格式化 2024-10-20 08:28:16

我正在考虑修改这段代码,以便alarmManager在唤醒时触发并在睡眠时停止,而服务内部是一个以特定时间间隔触发通知方法的定时器?有没有更好的方法来做到这一点?

在我看来,忘记思考“更好”的方法,这似乎是唯一的方法。使用一个计时器来控制(启用/禁用)另一个计时器并不奇怪,并且对我来说完全有意义。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文