What tools are available to test JobScheduler?

前端 未结 4 1915
我寻月下人不归
我寻月下人不归 2020-12-04 08:20

We\'re implementing a Job via JobScheduler for background loading of data. The job will fire about once a day. What tools are available for us to test this functionality (po

4条回答
  •  误落风尘
    2020-12-04 08:53

    This is working for me, without the need to use adb commands. It requires minSdk 21

    @RunWith(AndroidJUnit4.class)
    @TargetApi(VERSION_CODES.LOLLIPOP)
    public abstract class BaseJobServiceTest {
    
      protected final Context context() {
        return InstrumentationRegistry.getTargetContext();
      }
    
      protected final void launchJobAndWait(JobInfo jobInfo) throws InterruptedException {
        JobScheduler scheduler = (JobScheduler) context().getSystemService(Context.JOB_SCHEDULER_SERVICE);
    
        scheduler.schedule(jobInfo);
    
        while (jobExecutionPending(scheduler, jobInfo)) {
          Thread.sleep(50);
        }
      }
    
      private boolean jobExecutionPending(JobScheduler scheduler, JobInfo jobInfo) {
        if (VERSION.SDK_INT >= VERSION_CODES.N) {
          return scheduler.getPendingJob(jobInfo.getId()) != null;
        }
    
        List scheduledJobs = scheduler.getAllPendingJobs();
        for (int i = 0, size = scheduledJobs.size(); i < size; i++) {
          if (scheduledJobs.get(i).getId() == jobInfo.getId()) {
            return true;
          }
        }
    
        return false;
      }
    }
    

提交回复
热议问题