且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

后台服务的报警经理

更新时间:2022-12-27 08:50:22

试试这个:

public class PollReceiver extends WakefulBroadcastReceiver{
    static final String PERIOD = "period";
    @Override
    public void onReceive(Context context, Intent intent){
         startWakefulService(context,new Intent(context,MyService.class));
         long period = intent.getLongExtra(PERIOD,-1);
         if(period>0){
         scheduleExactAlarm(context,(AlarmManager)context.getSystemService(Context.ALARM_SERVICE),period)
         }
    }


    static void scheduleExactAlarm(Context context,AlarmManager alarms, long period){
    Intent i = new Intent(context,PollReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context,0,i,0);
    if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1){
        alarms.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() + period,pi);
    }
}

***专业教育学院这样打盹测试调度报警和它的作品。他们熄灭每隔15分钟。请查看 https://commonsware.com ,多数民众赞成在那里我发现调度重复报警的这个方法。

Ive tested scheduling alarms in this way in Doze and it works. They go off every 15 minutes. Check out https://commonsware.com , thats where I found this method of scheduling a repeating alarm.