在開發Andorid程序的時候,難免會牽扯到退出整個應用程序的情況,怎麼完全退出呢?請參閱下面的關鍵代碼:
- import java.util.LinkedList;
- import java.util.List;
- import Android.app.Activity;
- import android.app.AlertDialog;
- import android.app.Application;
- import android.content.DialogInterface;
- import android.content.Intent;
-
- public class SysApplication extends Application {
- private List<Activity> mList = new LinkedList<Activity>();
- private static SysApplication instance;
-
- private SysApplication() {
- }
-
- public synchronized static SysApplication getInstance() {
- if (null == instance) {
- instance = new SysApplication();
- }
- return instance;
- }
-
- // add Activity
- public void addActivity(Activity activity) {
- mList.add(activity);
- }
-
- public void exit() {
- try {
- for (Activity activity : mList) {
- if (activity != null)
- activity.finish();
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- System.exit(0);
- }
- }
-
- @Override
- public void onLowMemory() {
- super.onLowMemory();
- System.gc();
- }
-
- }
在每個Activity的onCreate方法中添加類似代碼:
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- SysApplication.getInstance().addActivity(this);
- }
在需要退出程序的時候,調用:
- SysApplication.getInstance().exit();
簡而言之,通過單例模式把每個Activity 的引用添加到一個全局鏈表中,每次退出程序調用System.exit(0)時,先調用鏈表中Activity 的finish方法。