当设备处于睡眠模式时,AlarmManager.setInexactRepeating可以不广播意图吗?

时间:2013-11-21 04:07:01

标签: android broadcastreceiver alarmmanager sleep

我有一个非常简单的类,用于设置和取消AlarmManager以广播意图:

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

我在我的活动的setAlarm(Context context)方法和onCreate()中的cancelAlarm(Context context)中调用了onDestroy()方法。然后在我的Activity的onCreate()方法中,我注册一个BroadcastReceiver来监听这个AlarmManager广播的意图并执行一些任务(同时获取唤醒锁以保证执行任务):

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

当手机处于睡眠模式时,我的AlarmManager是否可能不播放意图,即使我使用RTC_WAKEUP类型并且我在BroadcastReceiver中获得了WakeLock

到目前为止,我在多种设备中再现的经验是,我的设备处于睡眠模式的第一天晚上会播出意图(我的应用程序在白天不断运行),但是之后,它从未在晚上广播意图试。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

试试这个

     SystemClock.elapsedRealtime()

替换为

    System.currentTimeMillis()