Skip to content

Instantly share code, notes, and snippets.

@engmms
Forked from CreatorB/OnBackPressed.java
Created March 8, 2018 20:58
Show Gist options
  • Save engmms/490251f198bdfe4f500bdf366bdc2c11 to your computer and use it in GitHub Desktop.
Save engmms/490251f198bdfe4f500bdf366bdc2c11 to your computer and use it in GitHub Desktop.
How to Exit App When Press Back Button - Android
///////////////////////////////BACK-BUTTON-PRESSED/////////////////////////////
//////////////////////////////////creatorb////////////////////////////////////
//You can choose one method ;)
//PopUp
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
WelcomeActivity.super.onBackPressed();
}
}).create().show();
}
//Set Class to Top of App and no history
Intent launchNextActivity;
launchNextActivity = new Intent(B.class, A.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);
//Exit When Back and Set no History
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//***Change Here***
startActivity(intent);
finish();
System.exit(0);
//Styling for double press back button
private static long back_pressed;
@Override
public void onBackPressed(){
if (back_pressed + 2000 > System.currentTimeMillis()){
super.onBackPressed();
}
else{
Toast.makeText(getBaseContext(), "Press once again to exit", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
}
//For clear your history when back pressed, You can add android:noHistory="true" on your manifest.xml
<-- <activity
android:name="id.creatorb.math.Quiz"
android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize"
android:label="@string/app_name"
android:noHistory="true"
android:screenOrientation="portrait" >
</activity> -->
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment