在Android O上啟動Service遇到問題記錄

記錄場景:Android 8.0 有一項(xiàng)復(fù)雜功能;系統(tǒng)不允許后臺應(yīng)用創(chuàng)建后臺服務(wù)。 因此,Android 8.0 引入了一種全新的方法,即 Context.startForegroundService(),以在前臺啟動新服務(wù)。

在系統(tǒng)創(chuàng)建服務(wù)后,應(yīng)用有五秒的時間來調(diào)用該服務(wù)的 startForeground() 方法以顯示新服務(wù)的用戶可見通知。如果應(yīng)用在此時間限制內(nèi)未調(diào)用 startForeground(),則系統(tǒng)將停止服務(wù)并聲明此應(yīng)用為 ANR。

但是目前在調(diào)用:context.startForegroundService(intent)時報(bào)如下ANR,startForegroundService()文檔說明在service啟動后能夠自動調(diào)用startForeground(),不知為何沒有調(diào)用?如有大神知道請告知,謝謝。

android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()

于是使用context.startService(intent),并在在service的onCreate方法中調(diào)用startForeground(),主動將其變?yōu)榍芭_服務(wù)。

NotificationChannel channel = new NotificationChannel("id","name", NotificationManager.IMPORTANCE_LOW);

NotificationManager manager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE); 

manager.createNotificationChannel(channel);

Notification notification = new Notification.Builder(service,"id").build();

startForeground(id, notification);

在api 26 中要使用Notification.Builder(Context, String) ,并且要指明 NotificationChannel 的Id. 如果不加則會提示:Developer warning for package XXX,F(xiàn)ailed to post notification on channel “null”.

當(dāng)然關(guān)于NotificationChannel的配置可以參考:https://developer.android.google.cn/reference/android/app/NotificationChannel.html

Notification.Builder參考:https://developer.android.google.cn/reference/android/app/Notification.Builder.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容