I am building an Android App. How to exit an Android App when back is pressed. Android version is 2.3.3 and above. The Android App goes to previous activity which i don\'t want.
Kotlin:
override fun onBackPressed() {
val exitIntent = Intent(Intent.ACTION_MAIN)
exitIntent.addCategory(Intent.CATEGORY_HOME)
exitIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(exitIntent)
}
Other codes have problems, some does not work and some needs API classification.
If you have more than one screen in history and need all other ones to be ignored. I recommend using this:
@Override
public void onBackPressed() {
finish();
}
// Finish current activity
// Go back to previous activity or closes app if last activity
finish()
// Finish all activities in stack and app closes
finishAffinity()
// Takes you to home screen but app isnt closed
// Opening app takes you back to this current activity (if it hasnt been destroyed)
Intent(Intent.ACTION_MAIN).apply {
addCategory(Intent.CATEGORY_HOME)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(this)
}
I found an interesting solution which might help.
I implemented this in my onBackPressed()
finishAffinity();
finish();
FinishAffinity removes the connection of the existing activity to its stack. And then finish helps you exit that activity. Which will eventually exit the application.
I know its too late, but no one mentioned the code which i used, so It will help others.
this moveTaskToBack
work as same as Home Button. It leaves the Back stack as it is.
public void onBackPressed() {
// super.onBackPressed();
moveTaskToBack();
}
Some Activities you don't actually want to open again when the back button is pressed, such as Splash Screen Activity, Welcome Screen Activity and Confirmation Windows. Actually, you don't need this in the activity stack. You can do this using=> open Manifest.xml file and add an attribute
android:noHistory="true"
to these activities.
<activity
android:name="com.example.shoppingapp.AddNewItems"
android:label=""
android:noHistory="true">
</activity>
OR
Sometimes you want to close the entire application on a certain back button press. Here the best practice is to open up the home window instead of exiting the application. For that, you need to override the onBackPressed() method. Usually, this method opens up the top activity in the stack.
@override
public void onBackPressed(){
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
OR
On back button pressed you want to exit that activity and also you don't want to add this to the activity stack. Call finish() inside the onBackPressed() method. It will not close the entire application, it will just go to the previous activity in the stack.
onBackPressed() - Called when the activity has detected the user's press of the back key.
public void onBackPressed() {
finish();
}