Android电池在SDK中

有没有办法从Android SDK获取电池信息? 如电池剩余寿命等? 我无法通过文档find它。

您可以注册一个意图接收器接收广播ACTION_BATTERY_CHANGED: http : //developer.android.com/reference/android/content/Intent.html#ACTION_BATTERY_CHANGED 。 该文件说,广播是粘性的,所以即使在电池状态改变发生后,你也可以抓住它。

下面是一个快速的例子,可以帮助您了解电池的使用量,电池电压和温度。

将以下代码粘贴到一个活动中:

@Override public void onCreate() { BroadcastReceiver batteryReceiver = new BroadcastReceiver() { int scale = -1; int level = -1; int voltage = -1; int temp = -1; @Override public void onReceive(Context context, Intent intent) { level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1); voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1); Log.e("BatteryManager", "level is "+level+"/"+scale+", temp is "+temp+", voltage is "+voltage); } }; IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryReceiver, filter); } 

在我的手机上,每10秒输出一次:

ERROR/BatteryManager(795): level is 40/100 temp is 320, voltage is 3848

所以这就意味着电池充满了40%,温度是32.0摄氏度,电压是3.848伏特。

  public static String batteryLevel(Context context) { Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100); int percent = (level*100)/scale; return String.valueOf(percent) + "%"; } 

我需要有一个电池监视器,并检查水平和状态。 我正在开发MonoForAndroid,所以这就是我想出的。 我把它放在这里,以防有人有类似的要求。 (我已经testing过这个并且很好地工作)。

 try { var ifilter = new IntentFilter(Intent.ActionBatteryChanged); Intent batteryStatusIntent = Application.Context.RegisterReceiver(null, ifilter); var batteryChangedArgs = new AndroidBatteryStateEventArgs(batteryStatusIntent); _Battery.Level = batteryChangedArgs.Level; _Battery.Status = batteryChangedArgs.BatteryStatus; } catch (Exception exception) { ExceptionHandler.HandleException(exception, "BatteryState.Update"); throw new BatteryUpdateException(); } namespace Leopard.Mobile.Hal.Battery { public class AndroidBatteryStateEventArgs : EventArgs { public AndroidBatteryStateEventArgs(Intent intent) { Level = intent.GetIntExtra(BatteryManager.ExtraLevel, 0); Scale = intent.GetIntExtra(BatteryManager.ExtraScale, -1); var status = intent.GetIntExtra(BatteryManager.ExtraStatus, -1); BatteryStatus = GetBatteryStatus(status); } public int Level { get; set; } public int Scale { get; set; } public BatteryStatus BatteryStatus { get; set; } private BatteryStatus GetBatteryStatus(int status) { var result = BatteryStatus.Unknown; if (Enum.IsDefined(typeof(BatteryStatus), status)) { result = (BatteryStatus)status; } return result; } } } #region Internals public class AndroidBattery { public AndroidBattery(int level, BatteryStatus status) { Level = level; Status = status; } public int Level { get; set; } public BatteryStatus Status { get; set; } } public class BatteryUpdateException : Exception { } #endregion