android - 使用 alarmManager 和 service 仅在特定时间段执行计划通知

标签 android alarmmanager

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

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

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

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 在唤醒时间触发并在 sleep 时间停止,同时服务内部是一个以特定时间间隔触发通知方法的计时器?有没有更好的方法来做到这一点?

如有任何意见,我们将不胜感激。几天来我一直在努力在脑海中解决这个问题。

谢谢

编辑: @任何遇到此问题并打算使用计时器进行每日通知的人:

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

执行此操作的正确方法是将 AlarmManager 与一系列未决 Intent 一起使用,以在一天中的特定时间设置警报。这样可以确保即使手机处于待机状态,通知(或您希望当时发生的任何事情)仍会执行。

最佳答案

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?

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

关于android - 使用 alarmManager 和 service 仅在特定时间段执行计划通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4741757/

相关文章:

android - 在 Android 和 iOS 上使用 QT 和 QML 编辑视频

android - 它看起来像 : XHDPI PSD on Nexus 4 Screen?

android - 在 CollapsingToolbarLayout 上设置 contentscrim 颜色时出错

java - Android 中可离线使用的文本转语音

android - 广播接收器不会在 android Lollipop 设备上触发

android - 应用程序更新时警报的有效性

android - 使用 MVP 模型编写 "login"App 时出现问题

java - Alarmmanager 无法处理大秒数

android - 如何使用 flutter 警报管理器打开应用程序

android - 具有 Intent 服务的 AsyncTask(带 AlarmManager)