如何从另一个 activity 或底页对话框/片段中关闭 activity

How do I close an activity from another activity or bottomsheet dialog / fragmenr

尝试使用 finish()、finishAfinity() 和意图标记清除任务。

//Activity一个

public class A{
 public void finishActivity(){
     finish();
 }
}

//ActivityB

 public class B{

 Activity a = new ActivityA();
     a.finishActivity();
}

我希望 Activity A 被 Activity B

关闭

You can use a broadcast receiver to close Activity A from Activity B. Calling Activity A from B using an object will result into a null pointer exception. This is because, when Activity B starts, Activity A's onPause() method is called. Use BroadCastReceiver as below

BroadCastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent intent) {
            String action = intent.getAction();
            if (action.equals("finish_activity_a")) {
                // Finish activity
            }
        }
    };

Then register your broadcast receiver as follows:

try {

        //Register BroadcastReceiver
        registerReceiver(broadcastReceiver, new IntentFilter(BroadCastActions.actionUpdateAppOptions));

    } catch (IllegalArgumentException e){
        e.printStackTrace();
    }

You can register the broadcast receiver after initializing itin the onCreate method as above or in your onStart(), onResume(), onRestart() methods.

To UnRegister your broadcast receiver, do a follows:

try {

    //Check If BroadCast Was Received
    if (broadcastReceiver != null) {

        getActivity().unregisterReceiver(broadCastReceiver);
    }

} catch (IllegalArgumentException e){
    e.printStackTrace();

}

You can UnRegister your broadcast receiver in the onCreate() method or onStop(), onPause(), onDestroy() methods. I hope thi one helps. Feel free to comment below. Good Luck!