请先确定当前的充电状态。BatteryManager会通过一个包含充电状态的持续Intent广播所有的电池详情和充电详情。由于这是个持续 intent,因此您无需通过将传入null的registerReceiver作为接收器直接调用(如下一代码段所示)来注册BroadcastReceiver,系统会返回当前电池状态
intent。您可以在此处传入实际的BroadcastReceiver对象,不过我们会在下文中介绍如何处理更新,因此您不一定要执行此操作。IntentFilter ifilter =newIntentFilter(Intent.ACTION_BATTERY_CHANGED);Intent batteryStatus = context.registerReceiver(null, ifilter);如果设备正在充电,则您可以提取当前的充电状态和充电方式(无论是通过 USB 还是交流充电器),如下所示:// Are we charging / charged?int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS,-1);boolean isCharging = status ==BatteryManager.BATTERY_STATUS_CHARGING ||
status ==BatteryManager.BATTERY_STATUS_FULL;// How are we charging?int chargePlug = battery.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;通常,如果设备连接了交流充电器,您就应最大程度地提高后台更新频率;如果设备通过 USB 充电,请降低更新频率;如果电池在耗电,请进一步降低更新频率。
监控充电状态的变化
充电状态的改变就像设备连接电源那样容易,因此监控充电状态的变化并相应地调整刷新频率就很重要了。只要设备连接或断开电源,BatteryManager就会广播相应的操作。即使您的应用没有运行,也请务必接收这些事件,尤其是当这些事件会影响您启动应用以执行后台更新的频率时。因此,您应该通过在
intent 过滤器中定义ACTION_POWER_CONNECTED和ACTION_POWER_DISCONNECTED,在清单中注册BroadcastReceiver来侦听这两个事件。android:name=".PowerConnectionReceiver">android:name="android.intent.action.ACTION_POWER_CONNECTED"/>android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>在实施相关的BroadcastReceiver时,您可以按上一步骤所述提取当前的充电状态和充电方式。publicclassPowerConnectionReceiverextendsBroadcastReceiver{@Overridepublicvoid onReceive(Context context,Intent intent){int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);boolean isCharging = status ==BatteryManager.BATTERY_STATUS_CHARGING ||
status ==BatteryManager.BATTERY_STATUS_FULL;int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;}}