Android8.0出來後,爲了提高設備的性能,對於service也做了相應的改變。
- 如果針對 Android 8.0 的應用嘗試在不允許其創建後臺服務的情況下使用
[startService()]
函數,則該函數將引發一個[IllegalStateException]
。- 新的
Context.startForegroundService()
函數將啓動一個前臺服務。現在,即使應用在後臺運行,系統也允許其調用Context.startForegroundService()
。不過,應用必須在創建服務後的五秒內調用該服務的[startForeground()]
函數。
詳細android8.0變更請參考https://developer.android.google.cn/about/versions/oreo/android-8.0-changes
代碼實現
在原來 startService的代碼處修正
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//啓動前臺服務
context.startForegroundService(intent);
} else {
context.startService(intent);
}
在service類中onCreate()方法中新建一個Notification ,記住Android8.0後對於Notification新增了一個渠道channel;
最後加上startForeground(1, notification);
public void onCreate() {
super.onCreate();
//新建Notification
NotificationChannel channel = new NotificationChannel("1", "channel_name",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
Notification notification = new Notification.Builder(getApplicationContext(), "1").build();
startForeground(1, notification);
}