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

在 Android Service 中啟動 Activity:解決 ANR 的關鍵一行

編輯:關於 Android 程式設計

前陣子做一個小應用時,需要在 Service 中啟動(呼叫)一個 Activity,沒想到卻老是出現 ANR(Application Not Responding)。上網查了各種說法,實際嘗試後發現問題其實不難解決,只要加上一行程式碼即可。

問題程式碼

public class XXXService extends Service {
    public void onCreate() {
        super.onCreate();
        // 撥打電話
        Intent call = new Intent("android.intent.action.CALL", Uri.parse("tel:110"));
        startActivity(call);
    }
}

解決方案

關鍵就在於為 Intent 加上 FLAG_ACTIVITY_NEW_TASK 這個旗標:

public class XXXService extends Service {
    public void onCreate() {
        super.onCreate();
        // 撥打電話
        Intent call = new Intent("android.intent.action.CALL", Uri.parse("tel:110"));
        call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(call);
    }
}

關鍵語句就是 call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);。之所以需要它,背後的原因與 Android 系統的穩定性設計有關。

官方文件怎麼說

查看官方對 startActivity() 方法的說明,其中提到:

Note that if this method is being called from outside of an Activity Context, then the Intent must include the FLAG_ACTIVITY_NEW_TASK launch flag. This is because, without being started from an existing Activity, there is no existing task in which to place the new activity and thus it needs to be placed in its own separate task.

大致意思是:如果這個方法是被一個「非 Activity 的 Context」呼叫(例如 Service),那麼 Intent 就必須包含 FLAG_ACTIVITY_NEW_TASK 旗標。這是因為待建立的 Activity 並不是從一個已存在的 Activity 啟動的,任務堆疊中並沒有現成的任務可以容納它,因此它需要被放進一個屬於自己的、獨立的任務裡。

換句話說,Service 本身就沒有「任務堆疊」的概念,若直接把 Activity 塞進去,系統無所適從便會引發 ANR。加上這個旗標,等於明確告訴系統「請幫我開一個新任務來放這個 Activity」,問題自然迎刃而解。

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