SDK中的Android电池

有没有办法从Android SDK获取电池信息? 如电池续航时间等等? 我无法通过文档find它。

您可以注册一个Intent接收器来接收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,所以这就是我想出来的。 我把它放在这里以防有人有类似的要求。 (我测试了这个并且工作得很好)。

 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