Android 监听电量的状态

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_STATUS, 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
    原文作者:CoderMiner
    原文地址: https://www.jianshu.com/p/f4b710b13e6d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞