Android-进阶之退出当前应用的方式
- 比较粗鲁的方式-杀进程
android.os.Process.killProcess(android.os.Process.myPid()); |
- 使用ActivityManager的restartPackage方法,这种方法需要注意的是需要运行在Android 1.5 API Level为3以上才可以,并且需要权限
ActivityManager am = (ActivityManager)getSystemService (Context.ACTIVITY_SERVICE); |
所需权限:
<uses-permission android:name="android.permission.RESTART_PACKAGES"></uses-permission> |
- 使用FLAG_ACTIVITY_CLEAR_TOP 方式
使用FLAG_ACTIVITY_CLEAR_TOP 启动第一个Activity也就是MAIN的那个Activity然后在需要全部退出时调用finish
Intent intent = new Intent(); |
public abstract class MyApplication extends Application {
private static List<Activity> mActivityList = new LinkedList<Activity>();
@Override
public void onCreate() {
super.onCreate();
if(mActivityList!= null) {
mActivityList.clear();
}
registerActivityLifecycleCallbacks (new Application.ActivityLifecycleCallbacks() {
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if(mActivityList != null) {
mActivityList.add(activity);
}
}
public void onActivityDestroyed(Activity activity) {
if(mActivityList != null && mActivityList.contains(activity)) {
mActivityList.remove(activity);
}
}
public void onActivityPaused(Activity activity) {
}
public void onActivityResumed(Activity activity) {
}
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
public void onActivityStarted(Activity activity) {
}
public void onActivityStopped(Activity activity) {
}
});
}
public static void exitAppication(MixEngineService.callbackBefore callbackBefore) {
if(mActivityList != null) {
int activityCount = mActivityList.size();
for(int i =0;i<activityCount;i++) {
Activity activity = mActivityList.get(i);
if(activity != null) {
activity.finish();
activity.overridePendingTransition(0, R.anim.exitapplication_anim);
}
}
System.exit(0);
}
}
}