正在关闭来自 BroadcastReceiver 的 运行 应用程序

Closing running Application from BroadcastReceiver

在我的应用程序中,有一个条件每天都会检查,如果它为真,那么我希望我的应用程序在 运行 之间关闭,就像崩溃一样,堆栈也变得清晰。

我尝试并测试了很多解决方案,但没有找到符合我要求的解决方案。 我的 BroadcastReceiver

 public void onReceive(Context context, Intent intent) {
        PreferenceForApp prefs = new PreferenceForApp(context);
        Bundle bundle = intent.getExtras();
        if (bundle!=null){
            if(bundle.containsKey("exception")) {

//                String e = bundle.getString("exception")
                if(bundle.get("exception").toString().equalsIgnoreCase("http request failed with error_msg No Match Found")) {
                    prefs.setIsDeviceValidated(false);
                    prefs.setIsLogIn(false);
                    Log.i("Time", "Exception Occur");

                    Intent CSPIntent=new Intent(context,CSPLoginActivity.class);
                    CSPIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    CSPIntent.putExtra("close_activity", true);
                    Log.i("Time", "IntentExit");
                    context.startActivity(CSPIntent);
                }
            }
        }
    }
}

以及在 Activity 中完成的代码 我从 broadcastReceiver 调用:

if (getIntent().getBooleanExtra("close_activity",false)) {
    Log.i("Time", "ExitCSPLogin");
    this.finish();
}

此代码未在 运行 之间关闭 App。

您需要在您的 activity 中注册 BroadcastReceiver 并在您要关闭应用程序时向 BroadcastReceiver 发送广播。

在你的 Activity 中试试这个:

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.package.ACTION_CLOSE");;
BroadcastReceiver Receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
registerReceiver(Receiver, intentFilter);

在您的 onDestroy() 方法中 Activity 注销 BroadcastReceiver:

@Override
protected void onDestroy() {
    unregisterReceiver(Receiver);
    super.onDestroy();
}

现在当您想要关闭应用程序时发送广播到BroadcastReceiver:

Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.package.ACTION_CLOSE");
sendBroadcast(broadcastIntent);

希望对您有所帮助!

每次用户进入您的应用时,您都必须在应用的 mainActivity 的 onCreate 方法中检查以下条件。或者在 onResume 中,如果您想立即关闭您的应用程序

if (!prefs.getIsDeviceValidated()) {
    Log.i("Time", "ExitCSPLogin");
    this.finish();
}

我假设你的应用程序中有一个以上 activity,所以在每个 activity 中检查上面的标志,我们将把它放在主要 activity 中。允许用户在 he/she 到达 mainActivity

之前使用您的应用

注意:为您的应用创建广播接收器(添加到清单中),而不是为特定的 activity