java.lang.IllegalStateException: Not allowed to start service Intent  xxxx    app is in background uid UidRecord


Android 8.0 还对特定函数做出了以下变更:(1)如果针对 Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用 startService() 函数,     则该函数将引发一个 IllegalStateException。新的 Context.startForegroundService() 函数将启动一个前台服务。(2)即使应用在后台运行,系统也允许其调用 Context.startForegroundService()。不过,    应用必须在创建服务后的五秒内调用该服务的 startForeground() 函数。

1. 解决方案

// 启动服务的地方if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {        context.startForegroundService(new Intent(context, ServedService.class));    } else {        context.startService(new Intent(context, ServedService.class));    }// service 类内部  oncreate@Overridepublic void onCreate() {    super.onCreate();    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {       startForeground(1,new Notification()); //这个id不要和应用内的其他同志id一样,不行就写 int.maxValue()        //context.startForeground(SERVICE_ID, builder.getNotification());    }}

2. 推荐使用

If the service is running in a background thread by extending IntentService, 
you can replace IntentService with JobIntentService which is provided as part of Android Support Library

The best way is to use JobIntentService which uses the new JobScheduler for Oreo or the old services if not available.

Declare in your manifest:

And in your service you have to replace onHandleIntent with onHandleWork:public class YourService extends JobIntentService {    public static final int JOB_ID = 1;    public static void enqueueWork(Context context, Intent work) {        enqueueWork(context, YourService.class, JOB_ID, work);    }    @Override    protected void onHandleWork(@NonNull Intent intent) {        // your code    }}Then you start your service with:YourService.enqueueWork(context, new Intent());
https://stackoverflow.com/questions/46445265/android-8-0-java-lang-illegalstateexception-not-allowed-to-start-service-inten



更多相关文章

  1. android中各种permissiond详解
  2. android上传图片和参数(属性)到服务器
  3. android 服务前台运行startForeground
  4. 2018年Android最新面试题
  5. Android(安卓)Java和JavaScript代码相互调用
  6. Android(安卓)WebView与Javascript交互
  7. android中对服务的应用管理
  8. android笔记 AIDL 实现进程间通信
  9. 箭头函数的基础使用

随机推荐

  1. 如何使用phpunit测试用例测试ajax调用?
  2. 在数据库中存储行数或动态获取
  3. 3-腿和2腿的auth有什么区别?
  4. 网站优化之PHPCMS如何开启伪静态
  5. 如何在php中的谷歌分析中显示搜索概述
  6. 如何为MySQL中包含记录的现有表创建唯一
  7. PHP 轻量级的PHP类检测移动设备(包括平板
  8. 从PHP登录请求获取空的AJAX响应
  9. PHP-设计模式-依赖注入
  10. 键入提示 - 指定对象数组