Android 8.0開啓服務報錯,自定義廣播無法接收到

作者:燕歆波
導讀:8.0在廣播中調用startService報出異常;自定義廣播接收不到

項目中爲了防止服務在後臺被殺死,在service的onDestroy中發送了廣播,在廣播中重新打開service,結果報出了下面的錯誤:

Not allowed to start service Intent  xxxx   app is in background uid UidRecord...

Android 8.0 還對特定函數做出了以下變更:


1、如果針對 Android 8.0 的應用嘗試在不允許其創建後臺服務的情況下使用 startService() 函數,則該函數將引發一個 IllegalStateException。新的 Context.startForegroundService() 函數將啓動一個前臺服務。
 
2、即使應用在後臺運行,系統也允許其調用 Context.startForegroundService()。不過,
應用必須在創建服務後的五秒內調用該服務的 startForeground() 函數。

所以在啓動服務的地方需要針對8.0做出判斷

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
}else{
}

官方建議使用JobIntentService 實現:

If the service is running in a background thread by extending IntentService, 
you can replace IntentService with JobIntentService which is provided as part of Android Support Library
The best way is to use JobIntentService which uses the new JobScheduler for Oreo or the old services if not available.

還有一個問題就是,在8.0上,自定義廣播無法接受到廣播的問題:

官方文檔做出瞭解釋:
在這裏插入圖片描述解決方式有兩種:
1、使用動態註冊廣播接收器代替靜態註冊廣播接收器,建議使用JobScheduler

2、保留靜態註冊廣播接收器,但是需要發送顯式廣播,可以通過更改廣播方式設置ComponentName爲顯式廣播(指定包名):

Intent cast= new Intent("目標廣播接收器的action");
ComponentName comp = new ComponentName("目標廣播接收器所在應用的包名","目標廣播接收器類全路徑")
cast.setComponent(comp);
sendBroadcast(cast);

感謝:
https://blog.csdn.net/kongbaidepao/article/details/80259150
https://blog.csdn.net/michael_hejing/article/details/83830895

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章