Testing that Android AlarmManager has an alarm set.

Just a small post from our recent experience - how to test that Android AlarmManager has an alarm set.

The first approach is to do it programmatically - let's assume we registered our alarm as below:

Intent intent = new Intent("com.my.package.MY_UNIQUE_ACTION");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, 
                                      intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 1);

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60, pendingIntent); 

And now to check that registered above alarm is active we have to do the following:

boolean alarmUp = (PendingIntent.getBroadcast(context, 0, 
        new Intent("com.my.package.MY_UNIQUE_ACTION"), 
        PendingIntent.FLAG_NO_CREATE) != null);

if (alarmUp) {
    Log.d("myTag", "Alarm is already active");

The idea is to use PendingIntent.FLAG_NO_CREATE which according to android documentation is a flag indicating that if the described PendingIntent does not already exist, then simply return null instead of creating it (http://developer.android.com/reference/android/app/PendingIntent.html#FLAGNOCREATE).

The second solution is to use adb shell command:

After you run below command from the command line you'll receive the list of active alarms for provided package name:

adb shell dumpsys alarm | grep com.my.package
com.my.package +93ms running, 1 wakeups:
    +88ms 1 wakes 1 alarms: act=com.my.package.action.MY_UNIQUE_ACTION

More about dupmsys here - http://stackoverflow.com/questions/11201659/whats-android-adb-shell-dumpsys-tool-and-its-benefits.

Consider testing the alarm after:

device restarted
application was killed by the system or force stopped manually
application upgrade

Examples above were taken from this stackoverflow page - http://stackoverflow.com/questions/4556670/how-to-check-if-alarmmamager-already-has-an-alarm-set.