【发布时间】:2013-08-21 19:41:25
【问题描述】:
我在我的 android 应用的清单文件中声明了一个广播接收。一切正常。但是,当应用程序关闭时(通过 Android 设置中的“强制停止”按钮),广播接收器仍然响应广播并再次启动我的应用程序。
知道如何阻止这种情况吗?
谢谢
【问题讨论】:
标签: android android-intent android-manifest
我在我的 android 应用的清单文件中声明了一个广播接收。一切正常。但是,当应用程序关闭时(通过 Android 设置中的“强制停止”按钮),广播接收器仍然响应广播并再次启动我的应用程序。
知道如何阻止这种情况吗?
谢谢
【问题讨论】:
标签: android android-intent android-manifest
已经有一个answer。
基本上,您可以通过 Application 类的 onDestroy 方法中的 PackageManager 禁用广播接收器,然后在 Application 类的 onCreate 方法中再次启用它。
【讨论】:
应用程序没有 onDestroy 方法。它有 onTerminate 但从未调用过 =(
这是我的解决方案。我的应用程序中有 MainActivity,如果应用程序正常工作,它肯定必须处于活动状态。所以在广播接收器中,我总是检查 MainActiviy 是否正在运行。
public void onReceive(final Context context, final Intent intent){ 如果(isAppRunning(上下文)){ // 做我的处理 } 别的{ // 您可以在此处禁用接收器 Log.w(LOGTAG, "App 没有运行。忽略 " + 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;
}
【讨论】:
在Activity的onDestroy方法和onPause()中调用unregisterReceiver。 在 onCreate() 和 OnResume() 中注册。
【讨论】: