Search code examples
androidandroid-jobschedulerandroid-job

Android Jobscheduler - How to download large nos of images using Job Scheduler


I have a jobservice which takes image url and download the image into a folder. I want to know how can i create a jobscheduler it will set jobs for me to download the all 400 images. I have to download approx 400 images from different 400 http urls. Its a same job which will run one after another in a for loop.

below is code which i have written

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);
    }

Its not working and not triggering any request.


Solution

  • Add the following line in the last statment inside the for loop jobScheduler.schedule(builder.build());

    updated code :

    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);
        }