Search code examples
javaandroidsystemexit

Finish or Exit the application from secondary activity?


I am navigating the Activity 2, and by the time I press the back button, it should exit or finish the application without displaying the main activity. I am using ViewPager(Activity2), the code is working in backpress if I only navigate in the first page of the ViewPager, the moment I navigate the other pages, the code for exiting or finishing the application doesn't work and displays the mainActivity.

MainActivity

Intent myIntent = new Intent(MainActivity.this, Activity2.class);

Activity2

@Override
public void onBackPressed() {
      super.onBackPressed();
    this.finish();
    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(0);
    getParent().finish();
    Activity a1 = (Activity)this.getBaseContext();

    if(this.getParent()!=null){
        Activity a = (Activity)this.getParent().getApplicationContext();
        a.finish();
    }

    Log.i("Backpressed", "pressed");

}

Solution

  • This would work,

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);