Marco Virgolin Marco Virgolin - 1 year ago 113
Android Question

WakefulBroadcastReceiver doesn't receive PendingIntent from AlarmManager

I'm struggling on an app that must repeat a task with a specified interval. I want it to wakeup the device if needed. I have no idea why, but the WakefulBroadcastReceiver NEVER executes its onReceive method that should be triggered via AlarmManager. The problem persists with a normal BroadcastReceiver. I'm using a Lollipop 5.0.1 Nexus5, and time intervals are of 5-20 seconds.

Here's the code:

class mypackage.MainActivity

private void startRepeatingAlarm(){
this.wbr = new SimpleWakefulBroadcastReceiver();
this.registerReceiver(wbr, new IntentFilter("mypackage.FOO_ACTION"));
Intent i = new Intent("mypackage.FOO_ACTION");
i.setClass(this, SimpleWakefulBroadcastReceiver.class);

pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 1234, i, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), timeInterval, pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_SHORT).show();

class mypackage.SimpleWakefulBroadcastReceiver

public class SimpleWakefulBroadcastReceiver extends WakefulBroadcastReceiver{

public void onReceive(Context context, Intent intent) {
// This method gets NEVER called
Intent service = new Intent(context, SimpleWakefulService.class);
startWakefulService(context, service);

Answer Source

I'm going to stick my neck out here and guess that you haven't declared the broadcast receiver in your manifest:

<receiver android:name=".SimpleWakefulBroadcastReceiver"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download