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.statsdatom;
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 import javax.annotation.concurrent.GuardedBy;
32 
33 /**
34  * Handles callback from the framework {@link android.app.job.JobScheduler}.
35  * Runs a job for 0.5 seconds. Provides a countdown latch to wait on, by the test that schedules it.
36  */
37 @TargetApi(21)
38 public class StatsdJobService extends JobService {
39   private static final String TAG = "AtomTestsJobService";
40 
41   JobInfo mRunningJobInfo;
42   JobParameters mRunningParams;
43 
44   private static final Object sLock = new Object();
45 
46   @GuardedBy("sLock")
47   private static CountDownLatch sLatch;
48 
49   final Handler mHandler = new Handler();
50   final Runnable mWorker = new Runnable() {
51     @Override public void run() {
52       try {
53         Thread.sleep(500);
54       } catch (InterruptedException e) {
55       }
56 
57       jobFinished(mRunningParams, false);
58 
59       synchronized (sLock) {
60         if (sLatch != null) {
61           sLatch.countDown();
62         }
63       }
64     }
65   };
66 
resetCountDownLatch()67   public static synchronized CountDownLatch resetCountDownLatch() {
68     synchronized (sLock) {
69       if (sLatch == null || sLatch.getCount() == 0) {
70         sLatch = new CountDownLatch(1);
71       }
72     }
73     return sLatch;
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