1

我有一个作业服务,它获取图像 url 并将图像下载到一个文件夹中。我想知道如何创建一个作业调度程序,它将为我设置工作以下载所有 400 张图像。我必须从不同的 400 个 http 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);
    }

它不起作用,也没有触发任何请求。

4

1 回答 1

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);
    }
于 2018-11-08T08:16:18.233 回答