1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.server.cts.device.batterystats; 18 19 import android.annotation.TargetApi; 20 import android.app.job.JobInfo; 21 import android.app.job.JobParameters; 22 import android.app.job.JobScheduler; 23 import android.app.job.JobService; 24 import android.content.Context; 25 import android.os.Handler; 26 import android.util.Log; 27 28 import java.util.concurrent.CountDownLatch; 29 import java.util.concurrent.TimeUnit; 30 31 /** 32 * Handles callback from the framework {@link android.app.job.JobScheduler}. 33 * Runs a job for 1 second. Provides a countdown latch to wait on, by the test that schedules it. 34 */ 35 @TargetApi(21) 36 public class SimpleJobService extends JobService { 37 private static final String TAG = "SimpleJobService"; 38 39 public static final long JOB_EXECUTION_MS = 5000L; 40 41 JobInfo mRunningJobInfo; 42 JobParameters mRunningParams; 43 private static CountDownLatch sLatch; 44 45 final Handler mHandler = new Handler(); 46 final Runnable mWorker = new Runnable() { 47 @Override public void run() { 48 Log.i(TAG, "Running job"); 49 try { 50 Thread.sleep(JOB_EXECUTION_MS); 51 } catch (InterruptedException e) { 52 } 53 jobFinished(mRunningParams, false); 54 if (sLatch != null) { 55 sLatch.countDown(); 56 } 57 Log.i(TAG, "Finished job"); 58 } 59 }; 60 scheduleJob(Context context, JobInfo jobInfo)61 public static void scheduleJob(Context context, JobInfo jobInfo) { 62 JobScheduler js = context.getSystemService(JobScheduler.class); 63 js.schedule(jobInfo); 64 } 65 resetCountDownLatch()66 public static synchronized CountDownLatch resetCountDownLatch() { 67 sLatch = new CountDownLatch(1); 68 return sLatch; 69 } 70 71 @Override onCreate()72 public void onCreate() { 73 super.onCreate(); 74 } 75 76 @Override onStartJob(JobParameters params)77 public boolean onStartJob(JobParameters params) { 78 mRunningParams = params; 79 mHandler.post(mWorker); 80 return true; 81 } 82 83 @Override onStopJob(JobParameters params)84 public boolean onStopJob(JobParameters params) { 85 return false; 86 } 87 } 88