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.longevity.listeners; 17 18 import android.content.Context; 19 import android.content.Intent; 20 import android.content.IntentFilter; 21 import android.os.Bundle; 22 import android.support.annotation.VisibleForTesting; 23 24 import org.junit.runner.Description; 25 import org.junit.runner.notification.RunNotifier; 26 27 /** 28 * An {@link ActionListener} for terminating early on test end due to low battery. 29 */ 30 public final class BatteryTerminator extends RunTerminator { 31 @VisibleForTesting 32 static final String OPTION = "min-battery"; 33 private static final double DEFAULT = 0.05; // 5% battery 34 35 private final Context mContext; 36 private final double mMinBattery; 37 BatteryTerminator(RunNotifier notifier, Bundle args, Context context)38 public BatteryTerminator(RunNotifier notifier, Bundle args, Context context) { 39 super(notifier); 40 mMinBattery = Double.parseDouble(args.getString(OPTION, String.valueOf(DEFAULT))); 41 mContext = context; 42 } 43 44 /** 45 * Returns the battery level of the current device, in percent format (0.05 = 5%). 46 */ getBatteryLevel()47 private double getBatteryLevel() { 48 Intent batteryIntent = 49 mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 50 int level = batteryIntent.getIntExtra("level", -1); 51 int scale = batteryIntent.getIntExtra("scale", -1); 52 if (level < 0 || scale <= 0) { 53 throw new RuntimeException("Failed to get proper battery levels."); 54 } 55 return (double)level / (double)scale; 56 } 57 58 @Override testFinished(Description description)59 public void testFinished(Description description) { 60 if (getBatteryLevel() < mMinBattery) { 61 kill(String.format("battery fell below %.2f%%", mMinBattery * 100.0f)); 62 } 63 } 64 } 65