
你瞅啥?
有沒有經(jīng)歷過絕望,其他版本的手機(jī)都好好的啟動(dòng)服務(wù)并且正常開啟通知欄,oppo等個(gè)性十足的手機(jī)出現(xiàn)在你面前的時(shí)候,一臉懵逼有沒有?就像我的這個(gè)問題一樣,同樣是8.0的系統(tǒng),怎么oppo就那么個(gè)性?
在Android O中,有一個(gè)新的背景限制。嘗試啟動(dòng)startService()時(shí),將獲得IlleagalStateException,因此現(xiàn)在應(yīng)使用startForegroundService(),但是如果通過此新方法啟動(dòng)服務(wù),則會(huì)在屏幕截圖中看到類似的錯(cuò)誤。為避免此異常,您需要在startForegroundService()之后有5秒鐘的時(shí)間來創(chuàng)建startForeground(),以通知用戶您正在后臺(tái)工作。否則將崩潰出現(xiàn)這樣的崩潰信息:
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1961)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:7015)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:523)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
那么我們該如何解決呢?通過查閱資料發(fā)現(xiàn),解決起來也沒有那么復(fù)雜,看看怎么個(gè)套路!
1. 啟動(dòng)服務(wù),適配啟動(dòng)方案
//適配8.0以上的服務(wù)轉(zhuǎn)前臺(tái)服務(wù) 清單文件AndroidManifest中有配置 android.permission.FOREGROUND_SERVICE
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//適配8.0機(jī)制
context.startForegroundService(intent);
} else {
context.startService(intent);
}
2. service服務(wù)中的onCreate()中加上如下代碼
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { // 注意notification也要適配Android 8 哦
startForeground(ID, new Notification());// 通知欄標(biāo)識(shí)符 前臺(tái)進(jìn)程對(duì)象唯一ID
}