Android性能优化之电量优化

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
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值