android开发异常总结

2019-06-03  本文已影响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));
        }

 @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           startForeground(1,new Notification()); 
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读