后台服务的报警经理 [英] Alarm manager for background services
问题描述
我已经实现了报警经理每隔15分钟定期唤醒的后台服务。它工作正常,但由于纳入打盹模式的Android 6.0时,好像奇怪的行为,而不是在每15分钟醒来。虽然,我现在用的方法alarm.setExactAndAllowWhileIdle(),但仍然无法在空闲状态的工作。
I have implemented the alarm manager to wake up the background services every 15 mins periodically. It is working fine, but since the inclusion of DOZE mode Android 6.0, the seems like behaving strange and not waking up in every 15 mins. Although, I am using the method alarm.setExactAndAllowWhileIdle(), but still not working in Idle state
这是我实现报警管理方法
here is my method for implementing Alarm Manager
private void serviceRunningBackground()
{
final Intent restartIntent = new Intent(this, service.class);
restartIntent.putExtra("ALARM_RESTART_SERVICE_DIED", true);
alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Handler restartServiceHandler;
restartServiceHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
Log.d(TAG, " Marshmellow "+ TIMER_START_TIME);
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 900000, pintent);
} else {
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 900000, pintent);
}
sendEmptyMessageDelayed(0, TIMER_START_TIME);
}
};
restartServiceHandler.sendEmptyMessageDelayed(0, 0);
}
任何帮助将是AP preciated..thanks
Any help would be appreciated..thanks
推荐答案
试试这个:
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.
这篇关于后台服务的报警经理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!