• 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
  • 相关阅读:
    Java快速开发框架LML功能菜单管理
    性能测试知多少性能需求分析
    C++学习的方法以及四大名著
    .NET Micro Framework官方库+Controller Area Network
    PostgreSQL学习笔记
    幻风阁|kent.zhu'sBlog对google阅读器共享设计的再讨论
    【数据库事务日志碎片原理分析与方案】分析篇
    Windows 8 RC升级到RTM很顺利
    http://www.cnblogs.com/oneday/archive/2012/08/16/2643039.html
    Visual Studio 2012 Ultimate RTM 体验
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/6627387.html
Copyright © 2020-2023  润新知