android重启后台服务,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()方法即可。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值