Android性能优化-电量分析工具BatteryHistorian概述

摘要:Battery Historian是一个分析安卓5.0及以上版本的安卓设备电量相关信息与事件的工具。它允许应用开发者在时间轴上可视化系统和应用级别的事件,并且支持缩放查看功能。

1.环境支持

  使用Battery Historian需要安装Go语言、Python、Git,当然还有JDK,如果已安装可以忽略此节。

1.1.安装Go语言

  官网下载安装:http://golang.org/doc/install (被墙了)
  apt-get下载安装:sudo apt-get install golang
  安装完后需要设置环境变量:

1
2
3
    export GOPATH=$HOME/work
    export GOBIN=$GOPATH/bin
    export PATH=$PATH:$GOBIN

  如果用apt-get方式只需要在~/.bashrc下添加GOPATH就可以(注意修改了.bashrc环境变量要在新终端中才能生效),这个是之后Battery Historian源码会存放的位置。

1.2.安装Python

  需要2.7版本,不要下最新的3.0。
  官网下载安装:https://python.org/downloads
  apt-get下载安装:sudo apt-get install python2.7

1.3.安装Git

  官网下载安装:https://git-scm.com/download
  apt-get下载安装:sudo apt-get install git

2.Battery Historian安装与使用

2.1.下载源码

  shell中执行:

1
go get -d -u github.com/google/battery-historian/...

  这里会从github下把Battery Historian源码拉下来存放在$GOPATH目录。

2.2.安装

  首先在shell中切换到源码目录:

1
cd $GOPATH/src/github.com/google/battery-historian

  执行安装:

1
    go run setup.go

  正常情况下(在天朝一般不正常)安装完成,不过我这里出现以下错误:

1
2
3
4
Downloading Closure library...
Downloading Closure compiler...
Failed to download Closure compiler: Get http://dl.google.com/closure-compiler/compiler-20160208.zip: dial tcp 203.208.46.146:80: connection timed out
If this persists, please manually download the compiler from http://dl.google.com/closure-compiler/compiler-20160208.zip into the /home/yzw/develop/gopath/src/github.com/google/battery-historian/third_party/closure-compiler directory, unzip it into the /home/yzw/develop/gopath/src/github.com/google/battery-historian/third_party/closure-compiler diretory, and rerun this script.

  由于Google被墙了,导致Closure编译器无法下载,有两种方式解决:一是翻墙,另一种方式就是我常用的把下载地址放到迅雷里下载,然后把zip包放到目录“$GOPATH/src/github.com/google/battery-historian/third_party/closure-compiler”下,同时解压到这个目录下,不要删除掉zip包,否则会被认为未安装。继续执行一次安装提示:

1
2
3
Downloading 3rd-party JS files...
Generating JS runfiles...
Generating optimized JS runfiles...

到这一步就安装完成了。

2.3.运行

  启动服务:

1
go run cmd/battery-historian/battery-historian.go

  默认端口是9999,也可以自己定义端口:

1
go run cmd/battery-historian/battery-historian.go --port 9999

  服务启动后会建立一个http服务器,通过浏览器打开127.0.0.1:9999:

2.4.电量分析

  连接安卓设备生成bugreport:

1
adb bugreport > ~/bugreport

  在网页上选择“Browse”选择bugreport文件:
BatteryHistorian首页
  会出现一个”Submit”提交按钮,如果没有那只能说明你没有翻墙。分析网页源码里有很多Google相关的链接,需要一些JS和CSS支持视图化:

1
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/hot-sneaks/jquery-ui.css">

  这里没办法,只能翻墙(要免费用Shadowsocks),麻烦点就是用迅雷先下过来,再改网页内容。
  提交后返回分析结果:
BatteryHistorian分析页面1
  它能看出每个应用使用CPU的时长,WAKELOCK次数等,在电量一文中( http://www.laiwangyo.com/2016/04/12/Android%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96-%E7%94%B5%E9%87%8F/ )提到如果频繁使用_RTC定时器唤醒设备会导致功耗问题,查看App WakeLock Alarams:
BatteryHistorian分析页面2
  前两个应用基本上是1分钟唤醒一次CPU,这很有可能影响设备休眠时功耗。

3. 总结

  这里简单的介绍了Battery Historian安装和使用中碰到的问题与简单的电量分析方法,更多内容还是查看官方站点:https://github.com/google/battery-historian