Tuesday, August 30, 2016

Android - How to Kill the application on back button press.

The easiest way to do this is to clear all the top activities and call the finish() on the activities. The below code needs to be done by overriding the onBackPressed method.

    Intent intent = new Intent(this, LaunchActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("Exit", true);
    startActivity(intent);
    finish();

On the launch activity, now we need to have the below code at the end of onCreate, note that should not spin any new thread in the OnCreate method.

    if( getIntent().getBooleanExtra("Exit", false)){
        finish();
    }

In some cases, we may not want to have back traces left for specific activity on the activity stack. In such cases, we can just have the below code for each activity in the Android Manifest xml. for e.g. SplashScreen , Login Screen etc.

android:noHistory="true"

One another way is to have the homescreen shown while the app activity is not forcefully finished. The code below should be placed on OnBackPressed overriden method.

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


references:
http://stackoverflow.com/questions/3226495/how-to-exit-from-the-application-and-show-the-home-screen

No comments:

Post a Comment