Android8.0-启动Service遇到的问题

1、在android8.0之后调用startService(service);

异常信息:java.lang.IllegalStateException: Not allowed to start service Intent { cmp=***.SYGMessageService }: app is in background uid UidRecord{970b1b8 u0a198 TPSL bg:+4m17s479ms idle procs:1 seq(0,0,0)}
原因:Android 8.0 不再允许后台service直接通过startService方式去启动。
解决方案:改用startForegroundService(service);

 

2、在使用了Context.startForegroundService()后报错。

异常信息:Context.startForegroundService() did not then call Service.startForeground()
原因:在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。
解决方案:在Service.OnCreate的时候添加通知
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String channelId = "****Service";
String channelName = "**服务";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
//
Notification notification = new Notification.Builder(this, channelId)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("*****服务")
        .setContentText("随时准备接收消息...")
        .setAutoCancel(true)
        .setShowWhen(true)
        .build();
int id = 10011;
startForeground(id, notification);
}

 

你可能感兴趣的:(Android原创)