使用广播接收器 android 关闭应用程序

Using broadcast receiver android to close app

您好,我正在尝试使用广播接收器来触发某些操作

  1. Activity 将广播动作 "ACTION_EXIT" 并进入 Main Activity。

  2. 只要 Main Activity 收到广播 "ACTION_EXIT" 就会关闭应用程序。

我的代码在ActivityA(发送广播)

Intent broadcastIntent = new Intent(Beacon_MainActivity.this, MainActivity.class);
broadcastIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
broadcastIntent.setAction("com.package.ACTION_EXIT");
sendBroadcast(broadcastIntent);
finish();

Main Activity 上的代码接收广播并触发 ACTION_EXIT

private void registerReceiver(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.package.ACTION_EXIT");
        registerReceiver(myBroadcastReceiver, intentFilter);
    }

@Override
public void onResume() {
    registerReceiver();
    super.onResume();

}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(myBroadcastReceiver);
}

BroadcastReceiver myBroadcastReceiver =
        new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("onReceive", "Logout in progress");
                Toast.makeText(MainActivity.this, "what the ****", Toast.LENGTH_SHORT).show();
                finish();
            } 
        };

不知道为什么不行,谁能帮忙不胜感激

(app should be close when Main_Activity receive the broadcast on resume)

您的 MainActivity 暂停,而 ActivityA 为 运行,在此期间您的接收器未注册,因此无法接收广播。您可以通过结果转发来完成您想要的。

MainActivity中,用startActivityForResult()方法启动LoginActivity,重写onActivityResult()方法处理结果。

public static final int REQUEST_CODE = 0;
public static final String EXTRA_EXIT = "exit";
...

Intent actLogin = new Intent(this, LoginActivity.class);
startActivityForResult(actLogin, REQUEST_CODE);
...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case REQUEST_CODE:
            if(data == null) {
                return;
            }

            boolean shouldExit = data.getBooleanExtra(EXTRA_EXIT, false);

            if(shouldExit) {
                finish();
            }
            break;
        ...
    }
}

然后,在 LoginActivity 中,将 FLAG_ACTIVITY_FORWARD_RESULT 添加到用于启动 ActivityA 的 Intent。

Intent actA = new Intent(this, ActivityA.class);
actA.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(actA);
finish();

ActivityA中设置一个boolean值表示是否退出,添加到一个结果Intent中,设置为结果,完成Activity.

boolean shouldExit = ...            

Intent result = new Intent();
result.putExtra(MainActivity.EXTRA_EXIT, shouldExit);
setResult(Activity.RESULT_OK, result);
finish();

然后结果将传送回 MainActivity。这也可以仅使用结果代码来完成,但我更喜欢使用 Intent extras。