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 android.platform.test.longevity.listener; 17 18 import android.content.Context; 19 import android.content.Intent; 20 import android.content.IntentFilter; 21 import android.host.test.longevity.listener.RunTerminator; 22 import android.util.Log; 23 import androidx.annotation.VisibleForTesting; 24 25 import java.util.Map; 26 27 import org.junit.runner.Description; 28 import org.junit.runner.notification.RunNotifier; 29 30 /** 31 * A {@link RunTerminator} for terminating early on test end due to low battery. 32 */ 33 public final class BatteryTerminator extends RunTerminator { 34 @VisibleForTesting 35 static final String OPTION = "min-battery"; 36 private static final double DEFAULT = 0.05; // 5% battery 37 38 private final Context mContext; 39 private final double mMinBattery; 40 BatteryTerminator(RunNotifier notifier, Map<String, String> args, Context context)41 public BatteryTerminator(RunNotifier notifier, Map<String, String> args, Context context) { 42 super(notifier); 43 mMinBattery = args.containsKey(OPTION) ? Double.parseDouble(args.get(OPTION)) : DEFAULT; 44 mContext = context; 45 } 46 47 /** 48 * Returns the battery level of the current device, in percent format (0.05 = 5%). 49 */ getBatteryLevel()50 private double getBatteryLevel() { 51 Intent batteryIntent = 52 mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 53 int level = batteryIntent.getIntExtra("level", -1); 54 int scale = batteryIntent.getIntExtra("scale", -1); 55 if (level < 0 || scale <= 0) { 56 throw new RuntimeException("Failed to get proper battery levels."); 57 } 58 return (double) level / (double) scale; 59 } 60 61 @Override testFinished(Description description)62 public void testFinished(Description description) { 63 if (getBatteryLevel() < mMinBattery) { 64 kill(String.format("battery fell below %.2f%%", mMinBattery * 100.0f)); 65 } 66 } 67 68 /** 69 * Prints messages to logcat. 70 */ 71 @Override print(String reason)72 protected void print(String reason) { 73 Log.e(getClass().getSimpleName(), reason); 74 } 75 } 76