2

I have a broadcast receive declared in my android app's manifest file. Everything works ok. However, when the App is shut down (via the "Force Stop" button in the Android settings), the broadcast receiver still responds to broadcasts and fires up my Application again.

Any idea on how I can stop this?

Thanks

jtnire
  • 1,348
  • 5
  • 21
  • 32

3 Answers3

2

There is already an answer to that.

Basically you disable the Broadcast Receiver via the PackageManager in the onDestroy method of your Application class and enable it again in the onCreate Method of your Application class.

Community
  • 1
  • 1
Janusz
  • 187,060
  • 113
  • 301
  • 369
1

Application doesn't have onDestroy method. It has onTerminate but it's never called =(

Here is my solution. I have MainActivity in my app which for sure have to be active if app working. So in broadcast receiver I always check if MainActiviy is running.

public void onReceive(final Context context, final Intent intent){
   if(isAppRunning(context)){
       // Do my handling
   }
   else{
       // You can disable receiver here
       Log.w(LOGTAG, "App not running. Ignore " + LOGTAG + " call.");
   }
}

protected boolean isAppRunning(Context context){
    String activity = MainActivity.class.getName();
    ActivityManager activityManager = (ActivityManager)context.
                                     getSystemService(Context.ACTIVITY_SERVICE);

    List<RunningTaskInfo> tasks = activityManager.
                                  getRunningTasks(Integer.MAX_VALUE);

    for(RunningTaskInfo task : tasks){
        if(activity.equals(task.baseActivity.getClassName())){
            return true;
        }
    }
    return false;
}

B770
  • 1,272
  • 3
  • 17
  • 34
mc.dev
  • 2,675
  • 3
  • 21
  • 27
0

Call unregisterReceiver in the Activity's onDestroy method and onPause(). Register it in onCreate() and OnResume().

user936414
  • 7,574
  • 3
  • 30
  • 29