Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent



 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

@Override
public 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



你可能感兴趣的:(android,8.0,O,android,solution)