Android 8.0系统以后你该这样启动Service

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();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值