How to finish one activity from another activity in android

In android there are different ways to finish one activity from another activity ,one of them is using startActivityForResult intent ,another one is using interface which is having their own complexities. Here in this tutorial we will learn how to achieve this functionality in  a simpler way by sending a broadcast message to activity which should be closed

Steps

  • Create new project in android studio
  • New two activities
  • Implement the broadcast code in current activity
  • Code for finishing activity

Create New project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

New two activity’s

After creating the project a new activity will be automatically created if you haven’t change any defaults. Here in this example i am naming activity’s as FirstActivity.java and SecondActivity.java. So you either rename the activity or create another activity’s .You can create the activity by right clicking package name and then new->activity->basic activity.

Implement the broadcast code in current activity

Let us consider Activity to be closed as FirstActivity.java and current activity as SecondActivity.java. First we need to register a broadcast receiver in FirstActivity.java using the below code. This broadcast receiver will accept the trigger and that is how we can identify some activity needed to close this one and we can just do finish call.

BroadcastReceiver broadcast_reciever = new BroadcastReceiver() {

@Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
if (action.equals("finish")) {
//finishing the activity
finish();
}
}
};
registerReceiver(broadcast_reciever, new IntentFilter("finish"));

Code for finishing activity

Now add the following code to your SecondActivity.java in the place of action in which you need to close the FirstActivity.java.  So this code will sent a broadcast message to FirstActivity.java which we implemented broadcast receiver for closing that activtity.

Intent intent = new Intent("finish");
sendBroadcast(intent);
finish();

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

4 Comments

  1. Mehdi Raza Lakho July 25, 2019 Reply
  2. Mohit January 31, 2018 Reply
    • rameesAuthor January 31, 2018 Reply

Add a Comment

Your email address will not be published. Required fields are marked *