3

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!

janisz
  • 6,292
  • 4
  • 37
  • 70
Loren Kuich
  • 573
  • 3
  • 10
  • 25
  • you didn't mean app close, did you? I think you meant to minimize the app. On app close receiver wont intercept any actions ofcourse. – Anil P Babu Sep 20 '16 at 04:40

3 Answers3

17

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.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
0

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

JRowan
  • 6,824
  • 8
  • 40
  • 59
-1

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

@Override
public void onTerminate() {
    unregisterReceiver(mybroadcast);
    super.onTerminate();
}
Gladi
  • 415
  • 4
  • 16
  • 2
    don't use onTerminate(), public void onTerminate () Added in API level 1 This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so. http://developer.android.com/reference/android/app/Application.html#onTerminate() – Mohamed Heiba Aug 21 '13 at 12:18