最近遇到个问题:
后台Service启动正常启动后,锁屏状态下大概80秒左右Service就被暂停了(并没有被杀死),唤醒屏幕后就继续执行。
解决方法:
Service启动时创建一条通知,与其绑定,这样锁屏或者后台Service都不会被暂停或杀死。
代码如下:
在Service的onCreate中创建NotificationChannel 并且与服务绑定。
private NotificationManager notificationManager;
private String notificationId = "serviceid";
private String notificationName = "servicename";
@Override
public void onCreate() {
super.onCreate();
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.mipmap.log)
.setContentTitle("title")
.setContentText("text");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(notificationId);
}
Notification notification = builder.build();
return notification;
}