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

我的 Android 進階之旅:解決 Android 5.0 的「Service Intent must be explicit」崩潰

編輯:關於 Android 程式設計

1. 錯誤描述

同一份程式碼,在 Android 4.4 的小米 4 上跑得好好的,換到 Android 5.1 的華為 P7 上卻直接閃退。Logcat 給出的訊息是:

E/AndroidRuntime(12500): FATAL EXCEPTION: main
E/AndroidRuntime(12500): Process: com.xtc.watch, PID: 12500
E/AndroidRuntime(12500): java.lang.IllegalArgumentException: Service Intent must be explicit:
    Intent { act=com.xtc.kuwo.watch.MUSIC_PLAY_SERVICE (has extras) }
E/AndroidRuntime(12500):     at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1847)
E/AndroidRuntime(12500):     at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1876)
E/AndroidRuntime(12500):     at android.app.ContextImpl.startService(ContextImpl.java:1860)
E/AndroidRuntime(12500):     at android.content.ContextWrapper.startService(ContextWrapper.java:516)
E/AndroidRuntime(12500):     at com.xtc.watch.kuwo.activity.WatchMusicPlay.pauseMusic(WatchMusicPlay.java:314)
    ...

而啟動 Service 的程式碼看起來完全正常,只是用 action 隱式啟動:

Intent intent = new Intent();
intent.setAction(MUSIC_PLAY_SERVICE);
intent.putExtra("MSG", Constants.PlayerMsg.PAUSE_MSG);   // 暫停播放音樂
intent.putExtra("musicURL", musicURL);                   // 歌曲 URL
startService(intent);

2. 錯誤原因

有些時候我們會用隱式方式啟動 Service,但 Android 5.0 開始有了個硬性規定:Service Intent must be explicit。也就是說從 Lollipop 版本起,啟動 Service 必須採用顯式方式。

翻一下源碼(位置:sdk/sources/android-21/android/app/ContextImpl.java)就能看清楚。

startService(Intent service)

@Override
public ComponentName startService(Intent service) {
    warnIfCallingFromSystemProcess();
    return startServiceCommon(service, mUser);
}

startServiceCommon(Intent service, UserHandle user)

private ComponentName startServiceCommon(Intent service, UserHandle user) {
    try {
        validateServiceIntent(service);
        service.prepareToLeaveProcess();
        ComponentName cn = ActivityManagerNative.getDefault().startService(
                mMainThread.getApplicationThread(),
                service,
                service.resolveTypeIfNeeded(getContentResolver()),
                user.getIdentifier());
        if (cn != null) {
            if (cn.getPackageName().equals("!")) {
                throw new SecurityException("Not allowed to start service " + service
                        + " without permission " + cn.getClassName());
            } else if (cn.getPackageName().equals("!!")) {
                throw new SecurityException("Unable to start service " + service
                        + ": " + cn.getClassName());
            }
        }
        return cn;
    } catch (RemoteException e) {
        return null;
    }
}

validateServiceIntent(Intent service) —— 真正的檢查點

private void validateServiceIntent(Intent service) {
    if (service.getComponent() == null && service.getPackage() == null) {
        if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
            IllegalArgumentException ex = new IllegalArgumentException(
                    "Service Intent must be explicit: " + service);
            throw ex;
        } else {
            Log.w(TAG, "Implicit intents with startService are not safe: " + service
                    + " " + Debug.getCallers(2, 3));
        }
    }
}

邏輯非常清楚:當 targetSdkVersion >= LOLLIPOP,且 Intent 既沒有 Component 也沒有 Package 時,就直接拋出 IllegalArgumentException。在 5.0 之前,同樣的情況只會印一行警告,程式照樣跑,所以舊專案升級後才突然爆掉。

3. 解決方法

為 Intent 補上 packageName

原始程式碼:

Intent intent = new Intent();
intent.setAction(MUSIC_PLAY_SERVICE);
intent.putExtra("MSG", Constants.PlayerMsg.PAUSE_MSG);
intent.putExtra("musicURL", musicURL);
startService(intent);

修正後,只多加一行:

Intent intent = new Intent();
intent.setAction(MUSIC_PLAY_SERVICE);
// 少了這一句,Android 5.0 以上會拋出 Service Intent must be explicit
intent.setPackage(getPackageName());
intent.putExtra("MSG", Constants.PlayerMsg.PAUSE_MSG);
intent.putExtra("musicURL", musicURL);
startService(intent);

關鍵就是 intent.setPackage(getPackageName())。加上它之後,Intent 同時具備了 action 與 package,系統能在自己的應用內精準定位到目標 Service,不再需要去全域搜尋相符的元件。這也是 Google 官方推薦的做法。

另一種思路:改用顯式 Intent

如果不依賴 action 進行路由,更直接的方式是明確指定目標元件:

// 方式一:直接帶上 Class
Intent intent = new Intent(this, MusicPlayService.class);

// 方式二:透過 ComponentName
Intent intent = new Intent();
intent.setComponent(new ComponentName(this, MusicPlayService.class));

這兩種寫法完全繞過了 action 解析,效能上也略勝一籌,因為系統不需要額外做一次 Intent 比對。

4. 為什麼這個改動是合理的

隱式啟動 Service 存在本質上的風險:Intent 的 action 是全域命名空間,任何應用的 Service 只要宣告了相同的 action,就有可能被系統選中,造成服務被喚起到錯誤的執行體,甚至被惡意應用刻意攔截。強制顯式啟動,等於把「要啟動哪一個 Service」這件事從猜測變成宣告,安全性和可預測性都大幅提升。

因此與其把它當成升級時的絆腳石,不如趁機把所有 startService 都改成顯式寫法,一併消除潛在風險。

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