1

我已经实施了报警管理器来定期唤醒后台服务,每15分钟一次。它运行良好,但自从包含DOZE模式Android 6.0后,似乎表现得很奇怪,并且每15分钟就不醒来。虽然,我现在用的方法alarm.setExactAndAllowWhileIdle(),但仍然无法在空闲状态后台服务报警管理器

在这里工作是我实现报警管理方法

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); 
} 

任何帮助将是appreciated..thanks

+0

您正在测试现在的哪个版本? –

+0

Nexus 5上的Android 6.0预览, – user3290805

+1

使用'System.currentTimeMillis()+ 900000',它会在15分钟后触发警报。您需要在'service.java'的初始方法内再次编写这样的代码,以便在接下来的15分钟内设置警报。 –

回答

2

试试这个:

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,那是我发现这种安排重复警报的方法。

+0

的注释部分是否适用于Android 5.0和6.0 ? –