这是由于Android8.0以后启动后台服务的更改致使的。bash
嗯,不啰嗦了,直接贴完整代码吧。ui
// 这里是适配8.0以后如何启动后台服务
Intent intent = new Intent(context, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
}else {
context.startService(intent);
}
复制代码
下面是service中须要添加的代码,在onStartCommand的回调中添加的this
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//当sdk版本大于26
String id = "MyService";
String description = "my-service";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(id, description, importance);
manager.createNotificationChannel(channel);
notification = new Notification.Builder(this, id)
.setCategory(Notification.CATEGORY_MESSAGE)
// 这个icon无论用不用必须加!!!!!
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.build();
manager.notify(1, notification);
} else {
//当sdk版本小于26
notification = new NotificationCompat.Builder(this)
// 这个icon无论用不用必须加!!!!!
.setSmallIcon(R.drawable.ic_launcher)
.build();
manager.notify(1, notification);
}
startForeground(888, notification);
复制代码