Search code examples
androidandroid-fragmentsandroid-activitybroadcastreceiverandroid-fragmentactivity

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


Tried Using finish(), finishAfinity() and intent flag clear tasks.

//Activity A

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

//Activity B

 public class B{

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

I want Activity A to be closed by Activity B


Solution

  • 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!