1 // Copyright 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base; 6 7 import android.content.BroadcastReceiver; 8 import android.content.Context; 9 import android.content.Intent; 10 import android.content.IntentFilter; 11 import android.os.BatteryManager; 12 13 import org.chromium.base.annotations.CalledByNative; 14 import org.chromium.base.annotations.JNINamespace; 15 16 /** 17 * Integrates native PowerMonitor with the java side. 18 */ 19 @JNINamespace("base::android") 20 public class PowerMonitor { 21 private static PowerMonitor sInstance; 22 23 private boolean mIsBatteryPower; 24 createForTests()25 public static void createForTests() { 26 // Applications will create this once the JNI side has been fully wired up both sides. For 27 // tests, we just need native -> java, that is, we don't need to notify java -> native on 28 // creation. 29 sInstance = new PowerMonitor(); 30 } 31 32 /** 33 * Create a PowerMonitor instance if none exists. 34 */ create()35 public static void create() { 36 ThreadUtils.assertOnUiThread(); 37 38 if (sInstance != null) return; 39 40 Context context = ContextUtils.getApplicationContext(); 41 sInstance = new PowerMonitor(); 42 IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); 43 Intent batteryStatusIntent = context.registerReceiver(null, ifilter); 44 if (batteryStatusIntent != null) onBatteryChargingChanged(batteryStatusIntent); 45 46 IntentFilter powerConnectedFilter = new IntentFilter(); 47 powerConnectedFilter.addAction(Intent.ACTION_POWER_CONNECTED); 48 powerConnectedFilter.addAction(Intent.ACTION_POWER_DISCONNECTED); 49 context.registerReceiver(new BroadcastReceiver() { 50 @Override 51 public void onReceive(Context context, Intent intent) { 52 PowerMonitor.onBatteryChargingChanged(intent); 53 } 54 }, powerConnectedFilter); 55 } 56 PowerMonitor()57 private PowerMonitor() { 58 } 59 onBatteryChargingChanged(Intent intent)60 private static void onBatteryChargingChanged(Intent intent) { 61 assert sInstance != null; 62 int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); 63 // If we're not plugged, assume we're running on battery power. 64 sInstance.mIsBatteryPower = chargePlug != BatteryManager.BATTERY_PLUGGED_USB 65 && chargePlug != BatteryManager.BATTERY_PLUGGED_AC; 66 nativeOnBatteryChargingChanged(); 67 } 68 69 @CalledByNative isBatteryPower()70 private static boolean isBatteryPower() { 71 // Creation of the PowerMonitor can be deferred based on the browser startup path. If the 72 // battery power is requested prior to the browser triggering the creation, force it to be 73 // created now. 74 if (sInstance == null) create(); 75 76 return sInstance.mIsBatteryPower; 77 } 78 nativeOnBatteryChargingChanged()79 private static native void nativeOnBatteryChargingChanged(); 80 } 81