In my application i want exit from app when press back button, this my code:
@Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
it's work correctly but when i exit from app it does not exit completely and show empty page with my app logo and when i again press back button exit from app, How can i fix it???
EDIT :
I use this code instead of above but my app exit completely but i want it running at background and does not exit completely , how can i do it?
@Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}).setNegativeButton("no", null).show();
}
Use this code very simple solution
When you press back and then you finish your current activity(say A), you see a blank activity with your app logo(say B), this simply means that activity B which is shown after finishing A is still in backstack, and also activity A was started from activity B, so in activity, You should start activity A with flags as
Now your activity A is top on stack with no other activities of your application on the backstack.
Now in the activity A where you want to implement onBackPressed to close the app, you may do something like this,
The Handler here handles accidental back presses, it simply shows a
Toast
, and if there is another back press within 3 seconds, it closes the application.This one work for me.I found it myself by combining other answers
In my understanding Google wants Android to handle memory management and shutting down the apps. If you must exit the app from code, it might be beneficial to ask Android to run garbage collector.
You can also add finish() to the code, but it is probably redundant, if you also do System.exit(0)
Try this: