java.lang.IllegalStateException: Not allowed to start service Intent app is in background uid UidRecord
就是这样的一个bug才使我发现原来我的Android8.0并没有适配好!
先来看google开发文档对Android 8.0以后启动服务的一段描述:
也可以直接去查看8.0的变动:后台执行限制
之前启动Service的方法:
startService(new Intent(this, LockService.class));
启动Service的正确方式
1、添加权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
2、启动Service的方式:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this, LockService.class));
} else {
startService(new Intent(this, LockService.class));
}
3、在Service中的配置:
public class LockService extends Service {
public LockService() {
// super("Name for Service");
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("lock", "lock", NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager == null)
return;
manager.createNotificationChannel(channel);
//此处的channelId必须和上面NotificationChannel设置的id一致
Notification notification = new NotificationCompat.Builder(this, "lock")
.setAutoCancel(true)
.setCategory(Notification.CATEGORY_SERVICE)
.setOngoing(true)
.setPriority(NotificationManager.IMPORTANCE_LOW)
.build();
//注意 id不能为0
startForeground(107, notification);
}
}
}
还有一种错误:
Activity has leaked IntentReceiver that was originally registered here. Are you missing a call to unregisterReceiver()?
这种错误是因为你的注册广播没有成对出现,只有注册,没有注销代码,只需要添加如下代码即可:
@Override
public void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}