Hap*_*ppo 8 android android-jobscheduler
我签出了自Android API级别21以来可以使用的JobScheduler API.我想安排一项需要互联网的任务,每天只运行一次或每周运行一次(如果成功执行).我没有找到关于这种情况的例子.有人能帮我吗?谢谢.
Vic*_*tis 15
请按照一个简单的例子来说明您的问题,我相信它会对您有所帮助:
AndroidManifest.xml中:
<service android:name=".YourJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
Run Code Online (Sandbox Code Playgroud)
YourJobService.java:
class YourJobService extends JobService {
private static final int JOB_ID = 1;
private static final long ONE_DAY_INTERVAL = 24 * 60 * 60 * 1000L; // 1 Day
private static final long ONE_WEEK_INTERVAL = 7 * 24 * 60 * 60 * 1000L; // 1 Week
public static void schedule(Context context, long intervalMillis) {
JobScheduler jobScheduler = (JobScheduler)
context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
ComponentName componentName =
new ComponentName(context, YourJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
builder.setPeriodic(intervalMillis);
jobScheduler.schedule(builder.build());
}
public static void cancel(Context context) {
JobScheduler jobScheduler = (JobScheduler)
context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.cancel(JOB_ID);
}
@Override
public boolean onStartJob(final JobParameters params) {
/* executing a task synchronously */
if (/* condition for finishing it */) {
// To finish a periodic JobService,
// you must cancel it, so it will not be scheduled more.
YourJobService.cancel(this);
}
// false when it is synchronous.
return false;
}
@Override
public boolean onStopJob(JobParameters params) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
调度作业后,调用YourJobService.schedule(context, ONE_DAY_INTERVAL).它只会在连接到某个网络时调用,一旦在内部一天内调用...即每天一次连接到网络.
Obs.:Periodic工作只能完成调用JobScheduler.cancel(Job_Id),jobFinished()方法不能完成.
视频:如果你想把它改为"每周一次" - YourJobService.schedule(context, ONE_WEEK_INTERVAL).
obs.:Android L上的定期作业可以在您设置的范围内随时运行一次.