finish() not working as expected

7k views Asked by At

As I'm creating an android application in which first I've created main activity, then I've added splash activity along with the one normal activity.

So my problem is whenever I click on exit in my app it closes the main activity and returns that one normal activity in splash activity. I am using finish(); on exit button which is present in main activity.

So how can I exit the app which comes to android launcher screen

I've also tried creating new intent with Action Main but its only minimizing the app I want to close it

MainActivity.class

if (id == R.id.exit) {
            AlertDialog.Builder builder = new AlertDialog.Builder(homeActivity.this);
            builder.setMessage("Do You Want To Exit?").setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog alert = builder.create();
            alert.setIcon(R.drawable.ic_error_outline_black_24dp);
            alert.setTitle("Exit!!");
            alert.show();
      }
4

There are 4 answers

0
arjun On BEST ANSWER

When starting the MainAcitivity from SplashActivity set flags in intent as below and call finish() on SplashAcitivty

Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
0
faiyaz meghreji On

add this things in splash while navigating splash to mainActivity

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
0
Hector On

you can set android:excludeFromRecents="true" and android:noHistory="true" in you android Manifest file for the splash activity.

2
KayPee On

Try adding flag "Intent.FLAG_ACTIVITY_CLEAR_TOP" while you launch MainActivity from your SplashScreenActivity, as below:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);