Java – Broadcast Receiver Still Running after app close – Android

androidhandlejavasms

I'm using some code from this tutorial on how to receive SMS messages:

The code works perfectly, and does exactly what I want.

I am having 1 issue with it.

I want my app to run in the background, but when it's closed I want it to stop intercepting SMS messages.

My question is, why is my app still intercepting SMS messages after it's been closed?

I guess I have to find a "on close" handler and close the Broadcast Receiver then. (If there is a "on close" event handler..?).

If anyone can provide some insight I would be very grateful. Thanks!

Best Solution

By putting your BroadcastReceiver in your Manifest, it, by default, is always active. Therefore if you want it to only run while your Activity is shown, you'll want to enable/disable your BroadcastReceiver when your Activity resumes/pauses:

public void onResume()
{
    ComponentName component=new ComponentName(this, TextMessageReceiver.class);
    getPackageManager()
        .setComponentEnabledSetting(component,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

public void onPause()
{
    ComponentName component=new ComponentName(this, TextMessageReceiver.class);
    getPackageManager()
        .setComponentEnabledSetting(component,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
}

The alternative, is to declare your BroadcastReceiver in your Activity and then call registerReceiver and unregisterReceiver in the same lifecycle events.

Related Question