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 package com.android.server.cts.device.batterystats; 17 18 import static org.junit.Assert.assertTrue; 19 20 import android.app.AlarmManager; 21 import android.app.PendingIntent; 22 import android.content.BroadcastReceiver; 23 import android.content.Context; 24 import android.content.Intent; 25 import android.content.IntentFilter; 26 import android.os.SystemClock; 27 import android.util.Log; 28 29 import androidx.test.InstrumentationRegistry; 30 import androidx.test.runner.AndroidJUnit4; 31 32 import org.junit.Test; 33 import org.junit.runner.RunWith; 34 35 import java.util.concurrent.CountDownLatch; 36 import java.util.concurrent.TimeUnit; 37 38 @RunWith(AndroidJUnit4.class) 39 public class BatteryStatsAlarmTest { 40 private static final String TAG = "BatteryStatsAlarmTest"; 41 42 /** 43 * Set and fire a wakeup alarm 3 times. 44 */ 45 @Test testAlarms()46 public void testAlarms() throws Exception { 47 final int NUM_ALARMS = 3; 48 49 final Context context = InstrumentationRegistry.getContext(); 50 51 final Intent intent = new Intent("com.android.server.cts.device.batterystats.ALARM") 52 .setPackage(context.getPackageName()); 53 final IntentFilter inf = new IntentFilter(intent.getAction()); 54 55 final CountDownLatch latch = new CountDownLatch(NUM_ALARMS); 56 57 context.registerReceiver(new BroadcastReceiver() { 58 @Override 59 public void onReceive(Context context, Intent intent) { 60 Log.i(TAG, "Received: " + intent); 61 latch.countDown(); 62 }}, inf, Context.RECEIVER_EXPORTED_UNAUDITED); 63 64 final AlarmManager alm = context.getSystemService(AlarmManager.class); 65 for (int i = 0; i < NUM_ALARMS; i++) { 66 alm.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, 67 SystemClock.elapsedRealtime() + (i + 1) * 1000, 68 PendingIntent.getBroadcast(context, i, intent, PendingIntent.FLAG_MUTABLE)); 69 } 70 assertTrue("Didn't receive all broadcasts.", latch.await(60 * 1000, TimeUnit.SECONDS)); 71 } 72 } 73