Search code examples
androidandroid-activityback-button

Exit on backbutton pressed


I have two activities.

  1. MainActivity
  2. ListActivity

After some job in MainActivity, ListAllActivity starts. I want to exit the application when back button pressed from ListAllActivity. And my code for this is,

@Override
public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
    super.onBackPressed();
}

But, when I'm pressing the back Button from ListAllActivity , it simply brings me back to MainActivity.

The AndroidManifest entry for these Activities are :

<activity
        android:name="com.example.myapps.MainActivity"
        android:label="@string/loading" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.example.myapps.ListAllActivity"
        android:label="@string/title_activity_list_all" >

    </activity>

Please help.


Solution

  • Follow the below steps

    • From the MainActivity you need to call the finish() method after you pass intent to ListAllActivity
    • In the ListAllActivity call the finish() method on your button click or just press the back button as back button by default call finish() method.
    • In this way you will exit from your app.

    On the next button click of MainActivity write below code

    Intent intent=new Intent(MainActivity.this,ListAllActivity.class);
    startActivity(intent);
    finish();
    

    and on the ListAllActivity back button write below code

    finish();