Android 8.0 啟動后台service 出錯 IllegalStateException: Not allowed to start service Intent


錯誤原因:

Android 8.0 不再允許后台service直接通過startService方式去啟動, 具體行為變更如下:

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

解決方法:

1. 修改啟動方式

1 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
2     context.startForegroundService(intent);
3 } else {
4     context.startService(intent);
5 }

 

2. 並且在service里再調用startForeground方法,不然就會出現ANR

 1 context.startForeground(SERVICE_ID, builder.getNotification()); 

致謝參考: https://stackoverflow.com/questions/46445265/android-8-0-java-lang-illegalstateexception-not-allowed-to-start-service-inten


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM