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?