編輯:關於 Android 程式設計
同一份程式碼,在 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);
有些時候我們會用隱式方式啟動 Service,但 Android 5.0 開始有了個硬性規定:Service Intent must be explicit。也就是說從 Lollipop 版本起,啟動 Service 必須採用顯式方式。
翻一下源碼(位置:sdk/sources/android-21/android/app/ContextImpl.java)就能看清楚。
@Override
public ComponentName startService(Intent service) {
warnIfCallingFromSystemProcess();
return startServiceCommon(service, mUser);
}
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;
}
}
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 之前,同樣的情況只會印一行警告,程式照樣跑,所以舊專案升級後才突然爆掉。
原始程式碼:
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 官方推薦的做法。

如果不依賴 action 進行路由,更直接的方式是明確指定目標元件:
// 方式一:直接帶上 Class Intent intent = new Intent(this, MusicPlayService.class); // 方式二:透過 ComponentName Intent intent = new Intent(); intent.setComponent(new ComponentName(this, MusicPlayService.class));
這兩種寫法完全繞過了 action 解析,效能上也略勝一籌,因為系統不需要額外做一次 Intent 比對。
隱式啟動 Service 存在本質上的風險:Intent 的 action 是全域命名空間,任何應用的 Service 只要宣告了相同的 action,就有可能被系統選中,造成服務被喚起到錯誤的執行體,甚至被惡意應用刻意攔截。強制顯式啟動,等於把「要啟動哪一個 Service」這件事從猜測變成宣告,安全性和可預測性都大幅提升。
因此與其把它當成升級時的絆腳石,不如趁機把所有 startService 都改成顯式寫法,一併消除潛在風險。
Android 使用 SharedPreferences 實現數據存儲與讀取
開發中我們經常需要為用戶提供參數設置功能,比如 QQ 裡是否允許陌生人加我為好友這類開關。保存這類配置參數,桌面軟件通常用 ini 文件,J2SE 應用則多用 prope
Android Studio 下的 NDK JNI 開發完整入門
早些年用 Eclipse 搭配 NDK 研究 JNI 時,總覺得設定與開發都相當繁瑣。近來改用 Android Studio 開發 JNI,整體體驗順暢許多,於是趁機把流
AOSP 編譯疑難雜症集中報:從 libz 到 JDK 的完整排查
第一次自行編譯 Android 原始碼,幾乎每個人都會撞上一串錯誤。以下把常見問題與對應解法整理成一份清單,遇到時直接對照處理。 一、cannot find -lz 錯誤
把 Android 模組打成 jar 並用 ProGuard 混淆的實操筆記
又是一個睡不著的夜裡,來處理一件拖了很久的事:專案裡有部分程式碼想對外提供成 jar,而且不希望被人直接反編譯看光光。 步驟一:打包 jar 在 Eclipse 中