2012-03-23 48 views
1

我在我的android应用程序的清单文件中声明了广播接收。一切正常。但是,当应用程序关闭时(通过Android设置中的“强制停止”按钮),广播接收器仍会响应广播并再次启动我的应用程序。Android在应用程序关闭时禁用BroadcastReceiver

有关如何阻止此问题的任何想法?

感谢

回答

2

已经有一个answer

基本上,您可以通过应用程序类的onDestroy方法中的PackageManager禁用广播接收器,并在Application类的onCreate方法中再次启用它。

+1

谢谢,这个工作,但是这是应该做的正确的事吗? – jtnire 2012-03-23 12:17:22

0

呼叫unregisterReceiver在活动的方法的onDestroy和的onPause()。 在onCreate()和OnResume()中注册它。

+0

正如在问题中提到,我使用的清单给我的接收机。 – jtnire 2012-03-23 12:17:42

1

应用程序没有onDestroy方法。它有onTerminate但它从来不叫=(

这里是我的解决方案。我有MainActivity在我的应用程序,它肯定有,如果应用程序的工作是积极的。因此,在广播接收器,我总是检查是否MainActiviy运行。

 
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; }