Android(安卓)8.0系统以后你该这样启动Service
16lz
2021-01-26
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(); }
更多相关文章
- Android(安卓)Studio添加volley以及volley的简单用法
- Google Gson 加入到Android中, 打包编译混淆签名之后出现的错误
- Android: update api
- Android中AppCompatActivity找不到 与Fragment类型无法转换的问
- Android(安卓)调用堆栈跟踪
- android gridview布局添加多个title
- android studio添加第三方.os库
- android failed to start daemon 问题
- Android(安卓)Wifi 启动过程分析