Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 應用如何優雅地退出:完整流程拆解

編輯:關於 Android 程式設計

在 Android 中,「退出應用」其實不像桌面程式那樣直接關掉一個視窗就好。一個 App 往往由多個 Activity、背景服務、鬧鐘、通知與網路連線組成,因此真正的「乾淨退出」需要把這些資源逐一收尾。本文以一段實際的 SystemExit() 為例,說明完整的退出流程。

第一步:二次確認對話框

使用者按下離開時,先跳出一個 AlertDialog 詢問「是否退出本程式?」。按下「確定」才執行真正的清理,按下「取消」則直接返回,避免誤觸。

第二步:逐一關閉所有 Activity

App 在啟動時通常會把每個開啟過的 Activity 記錄在一個全域的 activityList 中。退出時遍歷這個清單,逐一呼叫 finish(),確保沒有残留在背景中的頁面。

第三步:取消鬧鐘、停止服務、清除通知

如果 App 註冊了週期性任務,必須記得取消對應的 PendingIntent 與 AlarmManager,並停止背景 Service,否則即使畫面關掉了,工作仍會在背景執行。此外也要把先前發出的通知從通知欄移除。

第四步:注銷連線並結束行程

若 App 有 VPN 這類需要主動登出的連線,別忘了呼叫登出方法;最後再以 System.exit(0) 結束整個行程。

參考程式碼

public void SystemExit() {
    AlertDialog exitDialog = new AlertDialog.Builder(SystemBaseActivity.this)
        .setTitle("提示")
        .setMessage("是否退出本程序?")
        .setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 1. 逐一關閉所有 Activity
                for (int i = 0; i < Global.activityList.size(); i++) {
                    if (Global.activityList.get(i) != null) {
                        Global.activityList.get(i).finish();
                    }
                }

                // 2. 取消廣播鬧鐘
                Intent iRefreshService = new Intent(Intent.ACTION_RUN);
                iRefreshService.setClass(sys_Context, BootReceiver.class);
                iRefreshService.setAction("ASYNCREFRESH");
                PendingIntent sender =
                    PendingIntent.getBroadcast(sys_Context, 0, iRefreshService, 0);
                AlarmManager am =
                    (AlarmManager) sys_Context.getSystemService(sys_Context.ALARM_SERVICE);
                am.cancel(sender);

                // 3. 停止背景服務
                Intent iRefresh = new Intent(Intent.ACTION_RUN);
                iRefresh.setClass(sys_Context, AsyncRefresh.class);
                sys_Context.stopService(iRefresh);

                // 4. 清除通知欄
                CommonUtil common = new CommonUtil();
                common.removeNotification(sys_Context, -1);

                // 5. 注銷 VPN
                if (StringUtil.vpnAuth != null) {
                    StringUtil.vpnAuth.VPNLogOut();
                }

                // 6. 結束行程
                System.exit(0);
            }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        })
        .create();
    exitDialog.show();
}

實務上要提醒的是:System.exit(0) 並非 Android 官方推薦的結束方式,系統本身會依記憶體狀況自動回收背景行程。上述做法比較像是為了「重啟 App」或「登出後徹底清空狀態」這類特定情境而設計。若只是想回到首頁,優先考慮攔截返回鍵並導回首頁 Activity,會是更符合 Android 設計哲學的做法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved