How do I exit my app programmatically from within my app? I have an exit button that brings up a dialog prompting the user to confirm exit. The back button does the same thing. This works usually. However, I'm also launching intents back to my MainActivity when I receive certain events, and the user taps on the notifications. I notice that when the intent is launched in this case, and then the user tries to exit, the app does not exit, but rather seems to go back to the previous instance. If I tap on 3 notifications which launches 3 intents back to MainActivity, I realize that I need to exit the app 3 times before it goes back to the homescreen.
Below is my exit code:
private AlertDialog alert;
if (alert != null) {
if (alert.isShowing()) {
alert.dismiss();
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Exit");
builder.setMessage("Are you sure you want to exit?").setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().finish();
System.exit(0);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alert = builder.create();
alert.show();
Here is my notification/intent code
Intent launchIntent;
launchIntent = new Intent(context, MainActivity.class);
launchIntent.putExtra("myType", type);
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder noti = new NotificationCompat.Builder(
context).setContentTitle(context.getResources().getString(R.string.app_name))
.setContentText(notificationMessage)
.setSmallIcon(R.drawable.ic_stat_notify)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL);
notificationManager.notify(notifyId, noti.build());