Search code examples
androidandroid-broadcast

Get PHONE_STATE event only when app is already running


I have an app for which I've added some functionality for when a call is coming in (phone ringing or answered). I did so by creating a BroadcastReceiver like this:

 <receiver android:name="mypackage.PhoneReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" >
                </action>

            </intent-filter>
        </receiver>

It is all working well but the problem is that it gets called even when my app isn't running, which makes sense but this triggers all sorts of other things on my app.

So the question is, can I have that BroadcastReceiver triggered only if my app (or a service I have) is running? or have my Application.onCreate() somehow know it is being created for the BroadcastReceiver and skip everything else it usually does?

Thanks.


Solution

  • You can take the receiver Off of the manifest, and register it programmatically in your code. Doing so, you can register/unregister whenever you want.