1.电量优化
电量优化首先我们要想到怎么去优化,要优化就要分析什么功能以及那些操作最耗电。
1.1 Battery Historian
Google提供了一个开源的电池历史数据分析工具 – Battery Historian。喜欢的同学可以去学习。Google在Udacity上发布了Android性能优化的在线课程。
1.1.1 安装
根据Battery Historian在github上的readme文件进行安装就行了。
1.1.2 使用
Battery Historian是Android 5.0开始引入的新API。通过下面的指令,可以得到设备上的电量消耗信息:
//得到整个设备的电量消耗信息
$ adb shell dumpsys batterystats > xxx.txt
//得到指定app相关的电量消耗信息
$ adb shell dumpsys batterystats > com.package.name > xxx.txt
得到原始电量消耗数据后,我们需要通过Google编写的一个python脚本把数据信息转换成可读性更好的html文件:
$ python historian.py xxx.txt > xxx.html
打开这个转换过后的html文件,可以看到生成的列表数据,这里的数据信息量很大,这里就不展开了。根据数据显示我们可以看到那个地方的功能模块比较耗电,这样可以针对性的对部门代码进行电量优化。
2.Track Battery Status & Battery Manager
//可以通过这段代码来获取手机的当前充电状态。
// It is very easy to subscribe to changes to the battery state, but you can get the current
// state by simply passing null in as your receiver. Nifty, isn't that?
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, filter);
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean acCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC);
if (acCharge) {
Log.v(LOG_TAG,"The phone is charging!");
}
上面描述了如何立即获取到手机的充电状态,得到充电状态信息之后,我们可以有针对性的对部分代码做优化。比如我们可以判断只有当前手机为AC充电状态时才去执行一些非常耗电的操作
/**
* This method checks for power by comparing the current battery state against all possible
* plugged in states. In this case, a device may be considered plugged in either by USB, AC, or
* wireless charge. (Wireless charge was introduced in API Level 17.)
*/
private boolean checkForPower() {
// It is very easy to subscribe to changes to the battery state, but you can get the current
// state by simply passing null in as your receiver. Nifty, isn't that?
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, filter);
// There are currently three ways a device can be plugged in. We should check them all.
int chargePlug = batterySt