finish(): 结束当前Activity,不会立即释放内存,遵循android内存管理机制
exit():结束当前组件,如Activity,并立即释放当前Activity所占的资源
KillProcess() : 结束当前组件,如Activity,并立即释放当前Activity所占的资源
restartPackage(): 结束整个APP,包括Service等其他组件。
特别注意:除了finish()方法可以调用Activity的生命周期方法如onStop()、onDestroy(),其余三种退出App均不会调用Activity的生命周期方法。除非,在调用这几个方法之前或者之后主动调用Activity的生命周期方法。如:
System.exit(int);
onDestroy();
注意一个问题:在android2.2之后,restartPackage方法不可以将应用程序结束,需要使用ActivityManager类的下面这个方法:
public void killBackgroundProcesses (String packageName)
api 文档说的很清楚:
public void restartPackage (String packageName) Since: API
Level 3 This method is deprecated. This is now just a wrapper for
killBackgroundProcesses(String); the previous behavior here is no
longer available to applications because it allows them to break other
applications by removing their alarms, stopping their services, etc.
另外,需要使用权限:
int currentVersion = android.os.Build.VERSION.SDK_INT;
if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1)
{
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//栈内复用模式
startActivity(startMain);
System.exit(0);
}
else {// android2.1
ActivityManager am = (ActivityManager)
getSystemService(ACTIVITY_SERVICE);
am.restartPackage(getPackageName());
}
设置入口activity的启动模式android:launchMode=”singleTask”,重写onNewIntent方法,
在退出activity时,设置intent.setAction(“exit_app”);然后跳转到栈底activity,
这样就可以清除栈底之外的所有activity,程序会自动执行onNewIntent方法,在该方法中获取它action,
如果等于”exit_app”,则关闭栈底activity,就可以退出App