通常Service都是运行在后台,后台运行的Service系统优先级较低,在系统内存不足的时候,后台运行的Service可能会被回收。当需求Service一直保持运行且在内存不足的情况下不会被回收,可以将Service设置为前台服务。
创建一个前台服务
public class MyService extends Service{
private static final String TAG = MyService.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ");
setForeground();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
return null;
}
/**
* 将Service设置为前台
*/
private void setForeground() {
Log.i(TAG, "setForeground: ");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("Foreground_Service",
"Foreground_Service", NotificationManager.IMPORTANCE_LOW);
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager == null) {
return;
}
manager.createNotificationChannel(channel);
Notification notification =
new NotificationCompat.Builder(this, "Foreground_Service")
.setAutoCancel(true)
.setCategory(Notification.CATEGORY_SERVICE)
.setOngoing(true)
.setPriority(NotificationManager.IMPORTANCE_LOW)
.build();
startForeground(101, notification);
}
}
}
Android 9以后上述的方法过了几秒后,Service会自动destory,试了试下面的方法
private String notificationId = "serviceid";
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//创建NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String notificationName = "servicename";
NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_MIN);
notificationManager.createNotificationChannel(channel);
}
startForeground(1, getNotification());
private Notification getNotification() {
Log.i(TAG, "getNotification: ");
Notification.Builder builder = new Notification.Builder(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(notificationId);
}
return builder.build();
}