4

Greetings! I'm working on an application that has a BroadcastReceiver listening on "android.intent.action.PHONE_STATE", which is run when the phone state is changed (I used it to run code when an incoming call is detected). This works fine on most of my test phones, but a few don't seem to trigger the receiver at all. However, once these problem phones are restarted everything works as expected.

Is there a reason these phones need to be restarted before the BroadcaseReceiver can pick anything up? Is there a way I can detect if it isn't running and manually "start" the BroadcaseReceiver? I'm stumped, so I'd appreciate any help you can offer.

Thank You.

Mac
  • 43
  • 1
  • 5

2 Answers2

16

To expand on the issue: starting from Android 3.1, installed applications are put in "STOPPED" state. To invoke BroadcastReceiver(s) from stopped application an additional broadcast intent flag is required.

More details: http://developer.android.com/sdk/android-3.1.html#launchcontrols

I created FLAG_INCLUDE_STOPPED_PACKAGES constant (=32) in my application (for pre-Android 3.1) and just add it to my broadcast intent intent.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);

Audrius
  • 2,836
  • 1
  • 26
  • 35
  • 1
    This is the answer that everyone is looking for. In case some do not understand how to use this: In your GCM BroadCast Receiver add to the intent FLAG_INCLUDE_STOPPED_PACKAGES and you should be able to receive notifications even when your app is "STOPPED". – superuserdo Jan 27 '15 at 02:39
3

Is there a reason these phones need to be restarted before the BroadcaseReceiver can pick anything up?

Assuming that your application has its BroadcastReceiver registered in the manifest for the PHONE_STATE broadcast, it should work immediately upon install. If it does not, it feels like a buggy ROM to me.

Is there a way I can detect if it isn't running and manually "start" the BroadcaseReceiver?

No, mostly because it's not running, usually, even when things are working. An instance of your BroadcastReceiver is created at the point of the Intent - <intent-filter> match, it is called with onReceive(), and the BroadcastReceiver is disposed of once onReceive() returns.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491