gpt4 book ai didi

android - JobScheduler 每 15 分钟执行一次

转载 作者:太空狗 更新时间:2023-10-29 13:47:57 24 4
gpt4 key购买 nike

我在我的应用程序中使用 JobScheduler。如果用户连接到 WIFI,我想在每个小时后上传文件,但是 onStartJob() 方法在一小时前被调用,大部分是在 15-20 分钟后被调用。以下是我的代码:

ComponentName componentName = new ComponentName(this,UploadService.class);
JobInfo info = new JobInfo.Builder(1,componentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) // change this later to wifi
.setPersisted(true)
.setPeriodic(60*60*10000)
.build();

JobScheduler scheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = scheduler.schedule(info);
if (resultCode==JobScheduler.RESULT_SUCCESS) {
Log.d(TAG,"JOb Scheduled");
} else {
Log.d(TAG,"Job Scheduling fail");
}

public class UploadService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
uploadFileToServer(params);
return true;
}

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

此处 uploadFileToServer(params); 在一小时前被调用。如何设置时间,使其仅在一小时后调用。提前致谢

最佳答案

JobInfo.Builder 上使用此方法 setPeriodic (long intervalMillis, long flexMillis)(在 API 24 中添加)并提供一个 flex interval 作为第二个参数:

long flexMillis = 59 * 60 * 1000; // wait 59 minutes before executing next job    

JobInfo info = new JobInfo.Builder(1,componentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) // change this later to wifi
.setPersisted(true)
.setPeriodic(60 * 60 * 1000, flexMillis)
.build();

重要 - 作业保证在弹性间隔(在最后一个作业完成后开始)之后运行,但不能保证在该时间之后立即运行,因此作业之间的持续时间可以超过 1 小时,具体取决于您的工作要求、系统状态等...

文档编号:https://developer.android.com/reference/android/app/job/JobInfo.Builder.html#setPeriodic(long,%20long)

Specify that this job should recur with the provided interval and flex. The job can execute at any time in a window of flex length at the end of the period.

Illustration


正如一些评论中已经推荐的那样,您应该开始使用新的 WorkManager (即使它还不是生产级别)具有与 JobScheduler 类似的功能,但它的最低 SDK 支持是 14,这将让您删除大量样板代码:)

关于android - JobScheduler 每 15 分钟执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51304185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com