最近公司出現了一個Bug,Service在後臺寫log時候一分鐘左右被殺死,或者運行一會就被殺死了,上網搜了一下原來是Android高版本爲了保護電量,流量什麼的,會在後臺殺死這些Service,現在我的做法是在通知欄加一條通知,讓他保證Service存活。
上代碼,在Service的onCreate方法裏寫:
private String notificationId = "serviceid";
private String notificationName = "servicename";
private void showNotification(){
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//創建NotificationChannel
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
startForeground(1,getNotification());
}
private Notification getNotification() {
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)//通知的圖片
.setContentTitle("通知的標題")
.setContentText("通知的內容");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(notificationId);
}
Notification notification = builder.build();
return notification;
}
寫完這些之後還需要添加一條權限:
<!--Android 9後臺運行Service-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />