Android 监听电量的状态
2016-11-15 本文已影响850人
CoderMiner
Android 电量相关的内容
监控手机电量的变化和充电状态
在BatteryManager
中有一个粘性广播,不需要BroadcastReceiver
作为接收器,在注册时将传入null
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intent = context.registerReceiver(null, filter);
从intent中就可以获取相关的电池的状态
当前电量
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); //电量的刻度
当前的充电状态
int status = intent.getIntExtra(BatteryManager.EXTRA_SCALE, BatteryManager.BATTERY_STATUS_UNKNOWN);
充电状态值:
状态 | 描述 |
---|---|
int BATTERY_STATUS_CHARGING = 2 | 充电中 |
int BATTERY_STATUS_DISCHARGING = 3 | 放电中 |
int BATTERY_STATUS_NOT_CHARGING = 4 | 未充电 |
int BATTERY_STATUS_FULL = 5 | 已充满 |
int BATTERY_STATUS_UNKNOWN = 1 | 状态未知 |
当前的充电方式
int plug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
充电的方式
方式 | 描述 |
---|---|
int BATTERY_PLUGGED_AC = 1 | 使用充电器充电 |
int BATTERY_PLUGGED_USB = 2 | 使用USB充电 |
int BATTERY_PLUGGED_WIRELESS = 4 | 使用无线方式充电 |
监听充电状态的变化
可以通过注册静态广播,监听 Intent.ACTION_POWER_CONNECTED
Intent.ACTION_POWER_DISCONNECTED
<receiver
android:name=".PowerReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
public class PowerReceiver extends BroadcastReceiver{
private static final String TAG = PowerReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_POWER_CONNECTED)){
Log.d(TAG, "power connected");
}else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)){
Log.e(TAG, "power disconnected");
}
}
}
确定基座的状态变化和类型
注册粘性广播ACTION_DOCK_EVENT
,来判断是插入底座,以及底座的类型
IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
Intent dockStatus = context.registerReceiver(null, ifilter);
int dockState = dockStatus.getIntExtra(EXTRA_DOCK_STATE, -1); //底座类型
boolean isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED; //是否插入了底座
底座的类型:
底座类型 | 描述 |
---|---|
int EXTRA_DOCK_STATE_CAR = 2 | 车载底座 |
int EXTRA_DOCK_STATE_DESK = 1 | 桌面底座 |
int EXTRA_DOCK_STATE_LE_DESK = 3 | 低端(模拟)桌面基座 API >= 11 |
int EXTRA_DOCK_STATE_HE_DESK = 4 | 高端(数字)桌面基座 API >= 11 |