最近遇到个问题:
后台Service启动正常启动后,锁屏状态下大概80秒左右Service就被暂停了(并没有被杀死),唤醒屏幕后就继续执行。网上搜了很多办法不好用知道看到一篇文章Service和Notification 给我提供了解决思路和解决办法。
解决思路:
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;
}
亲测有效!