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"  //重要1
/>
<uses-permission android:name="android.permission.WAKE_LOCK"/> //重要2

//@Override
//public IBinder onBind(@NonNull Intent intent) { //重要3,大坑,不能重写onBind方法,重写的话要返回super.onBind(),否则onHandleWork不会回调。
// return null;
//}

//重要4,重写onStartCommand方法时要返回super.onStartCommand()
Intent intent = new Intent(MainActivity.this,TestService.class);
intent.putExtra("key","value");
TestService.enqueueWork(MainActivity.this,intent);

 

posted @ 2019-05-29 18:53  yongfengnice  阅读(9930)  评论(0编辑  收藏  举报