一旦应用程序被杀死,JobScheduler onStartJob 就会延迟

JobScheduler onStartJob gets delayed once application gets killed

我不明白为什么 onStartJob 服务没有在 setOverrideDeadline(2000) 中提到的给定时间调用。

我正在安排这样的工作:

private void scheduleJob() {
    JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
            .setRequiresCharging(true)
            .setMinimumLatency(1000)
            .setOverrideDeadline(2000)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .setPersisted(true)
            .build();

    JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(myJob);
}

JobService 片段:

public class NetworkSchedulerService extends JobService implements
        ConnectivityReceiver.ConnectivityReceiverListener {

    private static final String TAG = NetworkSchedulerService.class.getSimpleName();

    private ConnectivityReceiver mConnectivityReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "Service created");
        mConnectivityReceiver = new ConnectivityReceiver(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "Service destroyed");
    }

    /**
     * When the app's MainActivity is created, it starts this service. This is so that the
     * activity and this service can communicate back and forth. See "setUiCallback()"
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        return START_NOT_STICKY;
    }


    @Override
    public boolean onStartJob(JobParameters params) {
        Log.i(TAG, "onStartJob" + mConnectivityReceiver);
        registerReceiver(mConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.i(TAG, "onStopJob");
        unregisterReceiver(mConnectivityReceiver);
        return true;
    }
}

清单:

 <service
            android:name=".NetworkSchedulerService"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE"/>

有人可以帮我解决这个问题吗?如果可能,请提供有关此延迟的详细说明。

尝试将 enabled 属性添加到清单中的 NetworkSchedulerService:

android:enabled="true"
 @Override
    public boolean onStartJob(JobParameters params) {
        Log.i(TAG, "onStartJob" + mConnectivityReceiver);
        return true;
    }

由于系统资源不可用,上述方法调用被延迟。 JobSceduler 没有必要在我在上面的代码中提到的给定截止日期内开始工作。

例如:setOverrideDeadline(2000)

一些 JobInfo 方法,如 setRequiresCharging()setRequiresBatteryNotLow() 可以减少延迟。

注意:此延迟在 Nougat 和 Oreo 设备中各不相同。所以有必要看看他们的延迟。