使用警报管理器重复后台服务

问题描述 投票:0回答:1

目前,我正在使用后台服务的新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的通知不会一直收到。另请注意,我需要在每天的同一时间进行通知。请帮助我。

android notifications alarmmanager background-service
1个回答
0
投票

您不能重复发出确切的警报。如果需要以精确的间隔重复一次,则需要在第一个间隔设置一个精确的警报,然后在警报触发时重新布防,以便在下一个间隔布防,并继续重复该过程。

© www.soinside.com 2019 - 2024. All rights reserved.