The Problem

If you want to call a function at a specific time or interval even if the smartphone is sleeping you have to use the AlarmManager.  But now the funny part starts! There could be several reasons that your receiver doesn't get called. This blog post could save you hours of frustration!

The possible reasons

1. Receiver not declared in AndroidManifest.xml
Declare the receiver in the Manifest-file:

2. Receiver in the Manifest xml is misspelled
Always remember that the whole Android-System is case sensitive. So check your spelling is correct in the AndroidMainfest.xml. Remember that the eclipse refactoring functions do not change packagename correctly if you use the short form like ".receivers.TestAlarmReceiver".

3. PendingIntent requestCode missing?
If you create a PendingIntent for your Receiver, please add an "requestCode" - even it is a random number! Without your "onReceive" code never get called!

4. AVD running for a long time (very tricky)
Be aware of using the AVDs especially if your working with "REALTIME_WAKEUP"  and SystemClock... So if you try to test your alarm, please restart the AVD or test on a real device!

Sample Code

BroadcastReceiver called by an AlarmManager:

public static void scheduleTestAlarmReceiver(Context context) {

   Intent receiverIntent = new Intent(context, TestAlarmReceiver.class);
   PendingIntent sender = PendingIntent.getBroadcast(context, 123456789, receiverIntent, 0);

   AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
   alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+startDelay, someDelay, sender);

}

BroadcastReceiver class:

public class TestAlarmReceiver extends BroadcastReceiver {

      @Override
      public void onReceive(Context context, Intent arg1) {
         // your code here!
      }

}

AndroidManifest.xml (insert inside the application-node)

<receiver android:name="net.fusonic.testapp.receivers.TestAlarmReceiver"></receiver>

comments powered by Disqus