Could AlarmManager.setInexactRepeating not broadcast intents when the device is in sleep mode?

时光总嘲笑我的痴心妄想 提交于 2020-01-15 16:35:31

问题


I have a very simple class that sets and cancels an AlarmManager to broadcast intents:

public class MyIntentsAlarm {

 public void setAlarm(Context context){
  AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  Intent i = new Intent("MY_ACTION");
  PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
  am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),5*60*1000L, pi);
 }

 public void cancelAlarm(Context context){
  Intent intent = new Intent("MY_ACTION");
  PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
  AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  alarmManager.cancel(sender);
 }
}

I call the setAlarm(Context context) method in the onCreate() method of my Activity and the cancelAlarm(Context context) in the onDestroy(). Then in the onCreate() method of my Activity I register a BroadcastReceiver to listen to the intents broadcasted by this AlarmManager and perform some task (while acquiring a wake lock to guarantee that the tasks are performed):

myActionAlarmReceiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
  Log.d(TAG, "MY_ACTION intent received");
  PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
  PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
  wl.acquire();
  runMyTask();
  wl.release();
 }
};
registerReceiver(myActionAlarmReceiver, new IntentFilter("MY_ACTION"));

Is it possible that my AlarmManager does not broadcast intents when the phone is in sleep mode, even if I use the RTC_WAKEUP type and I acquire a WakeLock in my BroadcastReceiver?

My experience so far, reproduced in multiple devices, is that the intents will be broadcasted the first night that my device is in sleep mode (my app is constantly running during the day), but then, it never broadcasts intents at night again.

Any ideas?


回答1:


Try this

     SystemClock.elapsedRealtime()

replacing with

    System.currentTimeMillis()


来源:https://stackoverflow.com/questions/20112247/could-alarmmanager-setinexactrepeating-not-broadcast-intents-when-the-device-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!