由於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);