Android 8.0以后使用后台Service服务JobIntentService的使用

由于Android8.0以后不能使用后台服务,使用Service需要使用ContextCompat.startForegroundService启动前台服务,而且通知栏有Notification显示该Service正在运行,这可能会带来不好的用户体验。
如果还是希望使用服务在后台默默工作,通过使用服务开启子进程等等,可以使用JobIntentService。下面的具体的代码:
public class TestService extends JobIntentService {

private static final int JOB_ID = 1000;

public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, TestService.class, JOB_ID, work);
}

@Override
protected void onHandleWork(@NonNull Intent intent) {
// TODO:
}
}

<service
android:name=".service.TestService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"   //需要
android:process=":test"/>

<uses-permission android:name="android.permission.WAKE_LOCK"/>  //需要

Intent intent = new Intent(MainActivity.this,TestService.class);
intent.putExtra("key","value");
TestService.enqueueWork(MainActivity.this,intent);

猜你喜欢

转载自www.cnblogs.com/yongfengnice/p/10945591.html