Android8.0之后禁止在后台启动服务的解决方案

方案一
将调用 startService启动Service 改为调用 startForegroundService

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     startForegroundService(intent);
} else {
     startService(intent);
}

方案二
使用JobIntentService(8.0)

 * Helper for processing work that has been enqueued for a job/service.  When running on
 * {@link android.os.Build.VERSION_CODES#O Android O} or later, the work will be dispatched
 * as a job via {@link android.app.job.JobScheduler#enqueue JobScheduler.enqueue}.  When running
 * on older versions of the platform, it will use
 * {@link android.content.Context#startService Context.startService}.

帮助处理已经为工作/服务排队的工作。在Android O或更高版本上运行时,工作将通过JobScheduler.enqueue作为作业分派。在旧版本的平台上运行时,它将使用Context.startService。
使用方法
1.创建一个JobIntentService

public class MyIntentJobService extends JobIntentService {

    private static final int JOB_ID = 10002;

    public static void startService(Context context, Intent work) {
        enqueueWork(context, MyIntentJobService.class, JOB_ID, work);
    }
    
    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        // 处理具体的逻辑

    }
}

2.声明权限并注册



3.直接调用MyIntentJobService的startService()方法即可。

你可能感兴趣的:(Android)