4

我正在尝试使用 job scheduler 执行定期任务。我想每 10 秒后调用一次服务,它可以正常工作几个小时,但有时它会停止工作,并且在设备重启后它不工作。

这是我尝试过的

ComponentName getAlertJobComponent = new ComponentName(context.getPackageName(), GetAlertJobService.class.getName());
JobInfo.Builder getAlertbuilder = new JobInfo.Builder(Constants.getAlertJobid, getAlertJobComponent);
getAlertbuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); // require unmetered network
getAlertbuilder.setRequiresDeviceIdle(true); // device should be idle
getAlertbuilder.setPeriodic(10 * 1000);
getAlertbuilder.setRequiresCharging(false); // we don't care if the device is charging or not
JobScheduler getAlertjobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
getAlertjobScheduler.schedule(getAlertbuilder.build());

我的工作服务是

public class GetAlertJobService extends JobService {
    @Override
    public boolean onStartJob(JobParameters params) {

        if (!Utility.isServiceRunning(GetAlertService.class, getApplicationContext())) {
            startService(new Intent(getApplicationContext(), GetAlertService.class));
        }
        jobFinished(params, false);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return true;
    }
}

GetAlertService是调用 Web 服务的服务

编辑

我还在引导接收器上添加了这个,如下所示

 public class Boot extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                ComponentName getAlertJobComponent = new ComponentName(context.getPackageName(), GetAlertJobService.class.getName());
                JobInfo.Builder getAlertbuilder = new JobInfo.Builder(Constants.getAlertJobid, getAlertJobComponent);
                getAlertbuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); // require unmetered network
                getAlertbuilder.setRequiresDeviceIdle(true); // device should be idle
                getAlertbuilder.setPeriodic(10 * 1000);
                getAlertbuilder.setPersisted(true);
                getAlertbuilder.setRequiresCharging(false); // we don't care if the device is charging or not
                JobScheduler getAlertjobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
                getAlertjobScheduler.schedule(getAlertbuilder.build());
            }
        }
    }

在清单中

<receiver
    android:name=".broadcastreceiver.Boot"
    android:enabled="true">

    <intent-filter android:priority="999">
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
4

1 回答 1

3

通过添加setPersisted(true)作业生成器来解决重置问题。对于长时间后停止工作-设备是否处于睡眠状态?如果是这样,它可能是一个打瞌睡的问题。

于 2017-01-30T06:44:02.083 回答