BatteryController.java
注册广播接收器,接收Intent.ACTION_BATTERY_CHANGED广播
之后调用BatteryStateChangeCallback cb.onBatteryLevelChanged(level, plugged)来回调刷新状态
其中,BatteryStateChangeCallback只是定义的一个interface:
public interface BatteryStateChangeCallback {
public void onBatteryLevelChanged(int level, boolean pluggedIn);
}
它的具体实在QuickSettingsModel.java中:
// BatteryController callback
@Override
public void onBatteryLevelChanged(int level, boolean pluggedIn) {
mBatteryState.batteryLevel = level;
mBatteryState.pluggedIn = pluggedIn;
mBatteryCallback.refreshView(mBatteryTile, mBatteryState);
}
PS:我们可以看到QuickSettingsModel这个类实现了好几个接口,这些接口都一些回调:
class QuickSettingsModel implements BluetoothStateChangeCallback,
NetworkSignalChangedCallback,
BatteryStateChangeCallback,
BrightnessStateChangeCallback,
RotationLockControllerCallback,
LocationSettingsChangeCallback {
…
}
继续往下看:
private RefreshCallback mBatteryCallback;
这里主要调用了refreshView方法来更新视图,看看它都做了些什么:
public void refreshView(QuickSettingsTileView ignored, State state) {
if (mShowWhenEnabled) {//这是一个开关,用户控制是否设置其可见性
mView.setVisibility(state.enabled ? View.VISIBLE : View.GONE);
}
if (state.iconId != 0) {//更新图标
mView.setImageDrawable(null); // needed to flush any cached IDs
mView.setImageResource(state.iconId);
}
if (state.label != null) {//更新文字
mView.setText(state.label);
}
}
至此,流程结束
如果需要在电池图标上显示当前电量百分比:可能需要修改如下地方:
public void refreshView(QuickSettingsTileView ignored, State state) {
if (mShowWhenEnabled) {
mView.setVisibility(state.enabled ? View.VISIBLE : View.GONE);
}
if (state.iconId != 0) {
mView.setImageDrawable(null); // needed to flush any cached IDs
mView.setImageResource(state.iconId);
}
if (state instanceof BatteryState) {
//如果走到这里说明更新的是电池?上面的iconId 是干啥的还有待进一步研究
Log.d(TAG, “quan #################################################### state.batteryLevel is ” + ((BatteryState)state).batteryLevel);
}
else {
Log.d(TAG, “quan #################################################### mBatteryState.batteryLevel is ” + mBatteryState.batteryLevel);
}
if (state.label != null) {
mView.setText(state.label);
}
}
另外,
BatteryMeterView.java中有关于状态栏电池初始化的代码。