How to finish an android application?

I need to finish an android application. For that i wrote

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application


To close application just call:

android.os.Process.killProcess(android.os.Process.myPid());

Otherwise due-to specific life-cycling of Android activities you can't be sure that application is closed/killed.


whenever you are starting a new activity use

myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myintent);

and in manifest file mention that activity as

<activity android:name=".<Activity Name>" >
        <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
     <category android:name="android.intent.category.DEFAULT" />
     </intent-filter>
       </activity>

Put this into your onClick or in onBackPressed:

moveTaskToBack(true);
finish()

Please read first this post from Google Android Developer Advocate Reto Meier : When to Include an Exit Button in Android Apps (Hint: Never)

What is th symptom that make you want to add an exit button ? If you need to clear the activity stack and always restart with a specific Activity, maybe you just have to tweak your activity manifest declaration with attributes like : android:clearTaskOnLaunch