首页 > 解决方案 > 使用警报管理器重复后台服务

问题描述

目前我正在开发一个使用后台服务的新 android 项目。因为 android 版本 >=Oreo 会自动终止服务。所以我使用AlarmManager。我需要在确切时间显示通知。通知时间在共享首选项中设置。我的警报处理程序正在关注

class AlarmHandler {
    private Context context;
    AlarmHandler(Context context){
        this.context=context;
    }
    void setAlarmManager(){
        Intent intent=new Intent(context,NotificationService.class);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(context,2,intent,0);
        AlarmManager alarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if(alarmManager!=null){
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,5000,60000,pendingIntent);
        }
    }
    void cancelAlarmManager(){
        Intent intent=new Intent(context,NotificationService.class);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(context,2,intent,0);
        AlarmManager alarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if(alarmManager!=null){
            alarmManager.cancel(pendingIntent);
        }
    }
}

我的通知服务如下

public class NotificationService extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String t1=timeFromsharedPreferences("t1");
        String t2=timeFromsharedPreferences("t2");
        String systemTime=getCurrentTime();
        if(systemTime.equals(t1)){
            notify();
        }else if(systemTime.equals(t2)){
            notify();
        }
    }
}

我使用以下代码启动 AlarmHandler

AlarmHandler alarmHandler=new AlarmHandler(this);
alarmHandler.cancelAlarmManager();
alarmHandler.setAlarmManager();

我还将广播接收器注册如下

<receiver android:name=".NotificationService" android:enabled="true" />

我的问题是有时它会跳过我的通知。时间安排在晚上 10:00 和早上 7:00。收到晚上 10 点的通知(请注意,我在晚上 10:00 使用电话或在晚上 10:00 前几分钟使用)。但是早上 7:00 的通知一直没有收到。另请注意,我需要每天在同一时间通知。请帮我。

标签: androidnotificationsalarmmanagerbackground-service

解决方案


你不能有一个重复的精确警报。如果您需要它以精确的间隔重复,您需要在第一个间隔设置一个精确的警报,然后在它触发时重新设置警报,以便为下一个间隔设置,并继续重复该过程。

编辑:

你需要做这样的事情

1.- compute delta in millis to next interval
2.- set exact alarm to fire in delta millis
3.- when the alarm fires, handle the event and then go to step 1

推荐阅读