I need to finish an android application. For that i wrote
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(
according to this answer,
just write this.finishAffinity();
and done!
Shameless copy of NeTeInStEiN's answer as I found it so useful (please up-vote his answer): Sending a running application to background programmatically
You can use either:
boolean sentAppToBackground = moveTaskToBack(true);
if(!sentAppToBackground){
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
More information here: http://developer.android.com/reference/android/app/Activity.html#moveTaskToBack(boolean)
Or simply:
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
According to Romain Guy a Android Framework Engineer, "You cannot simulate a press on the Home key.". So beware...
Check: http://osdir.com/ml/Android-Developers/2010-03/msg01887.html
Updated this answer according to: moveTaskToBack(true) returns false always
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
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()
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.