記錄場景: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