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、添加权限

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();    }

更多相关文章

  1. Android(安卓)Studio添加volley以及volley的简单用法
  2. Google Gson 加入到Android中, 打包编译混淆签名之后出现的错误
  3. Android: update api
  4. Android中AppCompatActivity找不到 与Fragment类型无法转换的问
  5. Android(安卓)调用堆栈跟踪
  6. android gridview布局添加多个title
  7. android studio添加第三方.os库
  8. android failed to start daemon 问题
  9. Android(安卓)Wifi 启动过程分析

随机推荐

  1. android 内存泄漏的分析
  2. Android(安卓)Studio第三十八期 - HIOS跳
  3. Android中拍照、图片、录音、视频和音频
  4. Android:Property Animation
  5. LinearLayout水平居中控制
  6. android之style样式-EditText样式
  7. Android官方命令深入分析之Device Monito
  8. Android运行main方法后java虚拟机停止运
  9. android:屏幕自适应
  10. Android笔记--handler机制