我正在尝试使用作业调度程序执行定期任务。我想在每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服务的服务
修改
我还在Boot接收器上添加了这个,如下所示
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>
答案 0 :(得分:3)
通过在作业构建器上添加setPersisted(true)
来解决重置问题。对于长时间工作的停止 - 设备是否处于睡眠状态?如果是这样,它可能是一个打瞌睡的问题。