Android O 后臺啟動Service崩潰問題
- 在 Android 8.0 (API26)之前,創(chuàng)建前臺服務(wù)的方式通常是先創(chuàng)建一個后臺服務(wù),然后將該服務(wù)推到前臺。
- Android 8.0 (API26)有一項復(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。
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
解決方法
- 將 調(diào)用 startService啟動Service 改為調(diào)用 startForegroundService
public static void start() {
Intent intent = new Intent(AppContext.me(), ScoreRefreshServer.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AppContext.me().startForegroundService(intent);
} else {
AppContext.me().startService(intent);
}
}
- 在service的onCreate方法中調(diào)用startForeground()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//NotificationCompat.Builder builder =
//new NotificationCompat.Builder(this, CHANNEL_ID)
// .setContentTitle("")
// .setContentText("");
NotificationChannel channel = new NotificationChannel(AppEnv.UMENG_CHANNEL, getString(R.string.yoyo_name), NotificationManager.IMPORTANCE_MIN);
channel.enableVibration(false);//去除振動
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) manager.createNotificationChannel(channel);
Notification.Builder builder = new Notification.Builder(getApplicationContext(), AppEnv.UMENG_CHANNEL)
// .setContentTitle("正在后臺運行")
.setSmallIcon(R.mipmap.logo);
startForeground(1, builder.build());//id must not be 0,即禁止是0
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。