Loren Kuich
Loren Kuich

Reputation: 603

Broadcast Receiver Still Running after app close - Android

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!

Upvotes: 3

Views: 10708

Answers (3)

ianhanniballake
ianhanniballake

Reputation: 199805

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.

Upvotes: 18

Gladi
Gladi

Reputation: 425

i would say override OnTerminate() on your application object and unregister your reciever there.

@Override
public void onTerminate() {
    unregisterReceiver(mybroadcast);
    super.onTerminate();
}

Upvotes: -1

JRowan
JRowan

Reputation: 7104

ive looked around on here and this is the conclusion ive come to

try{
        unregisterReceiver(mybroadcast);
    }catch(IllegalArgumentException e){
        Log.d("reciever",e.toString());
    }

i would say override onDestroy() and put it in there

Upvotes: 0

Related Questions