我有一个工作服务,该服务接受图像URL并将图像下载到文件夹中。我想知道如何创建JobScheduler,它将为我设置作业以下载所有400张图像。我必须从不同的400个URL下载大约400个图像。这是一项相同的工作,它将在for循环中一个接一个地运行。
下面是我写的代码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
JobScheduler jobScheduler = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
jobScheduler = context.getSystemService(JobScheduler.class);
}
jobScheduler.cancelAll();
int i = 1;
for (MyPojo pojo: complexObject.getTasks()) {
if (i < 100) {
PersistableBundle persistableBundle = new PersistableBundle();
persistableBundle.putInt("id", pojo.getId();
persistableBundle.putString("url", pojo.getImageURL());
persistableBundle.putString("parent_directory", "Mydirectory/.");
ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(12345, serviceComponent);
builder.setExtras(persistableBundle);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
builder.setOverrideDeadline(10 * 1000); // maximum delay
i++;
Log.d("i count is ", " " + i);
}
它不起作用,也不会触发任何请求。
答案 0 :(得分:1)
在for循环的最后一个语句中添加以下行 jobScheduler.schedule(builder.build());
更新的代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
JobScheduler jobScheduler = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
jobScheduler = context.getSystemService(JobScheduler.class);
}
jobScheduler.cancelAll();
int i = 1;
for (MyPojo pojo: complexObject.getTasks()) {
if (i < 100) {
PersistableBundle persistableBundle = new PersistableBundle();
persistableBundle.putInt("id", pojo.getId();
persistableBundle.putString("url", pojo.getImageURL());
persistableBundle.putString("parent_directory", "Mydirectory/.");
ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(12345, serviceComponent);
builder.setExtras(persistableBundle);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
builder.setOverrideDeadline(10 * 1000); // maximum delay
**jobScheduler.schedule(builder.build());**
i++;
Log.d("i count is ", " " + i);
}