Android 后臺啟動Service 8.0報錯記錄

報錯信息


如果針對 Android 8.0 的應(yīng)用嘗試在不允許其創(chuàng)建后臺服務(wù)的情況下使用 startService() 函數(shù),則該函數(shù)將引發(fā)一個 IllegalStateException。 新的 Context.startForegroundService() 函數(shù)將啟動一個前臺服務(wù)。現(xiàn)在,即使應(yīng)用在后臺運行, 系統(tǒng)也允許其調(diào)用 Context.startForegroundService()。不過,應(yīng)用必須在創(chuàng)建服務(wù)后的五秒內(nèi)調(diào)用該服務(wù)的 startForeground() 函數(shù)。?

解決方案

1.修改context.startService(i);為context.startForegroundService(i);


//8.0系統(tǒng)不允許后臺應(yīng)用創(chuàng)建后臺服務(wù)

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

context.startForegroundService(i);

}else {

context.startService(i);

}

2.被啟動Service調(diào)整為前臺服務(wù),否則會出現(xiàn)ANR

在Service的onCreate()方法中,注意Android 8.0版本通知欄創(chuàng)建方式

@Override

public void onCreate() {

super.onCreate();

? ? //2.被啟動Service調(diào)整為前臺服務(wù),否則會出現(xiàn)ANR

//在Service的onCreate()方法中,注意Android 8.0版本通知欄創(chuàng)建方式

? ? String id ="1";

? ? String name ="channel_name_1";

? ? NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

? ? Notification notification =null;

? ? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

NotificationChannel mChannel =new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);

? ? ? ? mChannel.setSound(null, null);

? ? ? ? notificationManager.createNotificationChannel(mChannel);

? ? ? ? notification =new Notification.Builder(this)

.setChannelId(id)

.setContentTitle(getResources().getString(R.string.app_name))

.setAutoCancel(false)// 設(shè)置這個標(biāo)志當(dāng)用戶單擊面板就可以讓通知將自動取消

? ? ? ? ? ? ? ? .setOngoing(true)// true,設(shè)置他為一個正在進(jìn)行的通知。他們通常是用來表示一個后臺任務(wù),用戶積極參與(如播放音樂)或以某種方式正在等待,因此占用設(shè)備(如一個文件下載,同步操作,主動網(wǎng)絡(luò)連接)

? ? ? ? ? ? ? ? .setSmallIcon(R.drawable.logo).build();

? ? }else {

NotificationCompat.Builder notificationBuilder =new NotificationCompat.Builder(this)

.setContentTitle(getResources().getString(R.string.app_name))

.setPriority(Notification.PRIORITY_DEFAULT)// 設(shè)置該通知優(yōu)先級

? ? ? ? ? ? ? ? .setAutoCancel(false)// 設(shè)置這個標(biāo)志當(dāng)用戶單擊面板就可以讓通知將自動取消

? ? ? ? ? ? ? ? .setOngoing(true)// true,設(shè)置他為一個正在進(jìn)行的通知。他們通常是用來表示一個后臺任務(wù),用戶積極參與(如播放音樂)或以某種方式正在等待,因此占用設(shè)備(如一個文件下載,同步操作,主動網(wǎng)絡(luò)連接)

? ? ? ? ? ? ? ? .setSmallIcon(R.drawable.logo);

? ? ? ? notification = notificationBuilder.build();

? ? }

startForeground(1, notification);

}



參考鏈接:Android 保活后臺啟動Service 8.0踩坑記錄 - QingTeng_CSDN的博客 - CSDN博客

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容