I have a BroadcastReceiver that can successfully catch a broadcast, but if I try to call another method from it, it won’t always work. Here’s my setup:
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (working == true) {
//toast to make sure we got here
doWork();
}
}
}
The toast within the if gets called, but doWork doesn’t execute. Has anyone dealt with a similar issue?
The Broadcast receiver doesn’t have the same context and life cycle as your application, you can’t do a lot of normal stuff in it. All your supposed to do is handle the event and return as quick as possible. In other words, start a service, or notify the user.
From: http://developer.android.com/reference/android/content/BroadcastReceiver.html
A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.
This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.
In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service.