美文网首页
android开发异常总结

android开发异常总结

作者: 砺剑锋成 | 来源:发表于2019-06-03 11:05 被阅读0次
  1. java.lang.IllegalStateException: Not allowed to start service Intent xxxx app is in background uid UidRecord

原因分析:
Android 8.0 有以下调整:
Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用 startService() 函数,则该函数将引发一个 IllegalStateException。

新的 Context.startForegroundService() 函数将启动一个前台服务。现在,即使应用在后台运行,系统也允许其调用 Context.startForegroundService()。

不过,应用必须在创建服务后的五秒内调用该服务的 startForeground() 函数。

解决方案:

  • 所以需要在启动服务的地方添加判断过滤
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, ServedService.class));
        } else {
            context.startService(new Intent(context, ServedService.class));
        }

  • 在服务的内部类oncreate方法上也需要添加过滤
 @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           startForeground(1,new Notification()); 
        }
    }

相关文章

网友评论

      本文标题:android开发异常总结

      本文链接:https://www.haomeiwen.com/subject/craqxctx.html