为什么要做电量优化

Android应用开发中,需要考虑的情况是,如何优化电量使用,让我们的app不会因为电量消耗过高被用户排斥,或者被其他安全应用报告。

什么样的行为会导致电量损耗过高

对于移动设备而言,有以下几种行为会导致设备电量的消耗增加

1.屏幕保持开启状态

2.蜂窝网络的频繁启动与关闭

如何观测我们的应用电量使用情况

可以先使用以下adb命令,生成我们应用的电量使用情况txt

adb kill-servers

adb devices

adb shell dumpsys batterystats --reset

1

2

3

adbkill-servers

adbdevices

adbshelldumpsysbatterystats--reset

从电脑拔出手机,操作一会我们的目标app,再接上电脑

adb kill-servers

adb devices

adb shell dumpsys batterystats --reset

1

2

3

adbkill-servers

adbdevices

adbshelldumpsysbatterystats--reset

然后再去https://github.com/google/battery-historian 下载zip文件

找到下载文件中的historian.py,拷贝到常用位置

接下把cmd转到刚刚存放文件的位置来运行

python historian.py battery.txt > battery.html

1

pythonhistorian.pybattery.txt>battery.html

运行结束后就得到了一个html文件,可以在浏览器打开查看

顶部是电量情况

最左边是各种行为

底部是时间间隔(如下图,点击查看大图)

1dc9a8a80f152b06f2d431ac3df32b7e.png

1fd91da50af52ab122275df9cb655e3e.png

优化API——PowerManager.WakeLock

PowerManager.WakeLock 可以通过 acquire()方法获得,使设备保持在获取时的状态。

在执行完任务之后,我们需要调用release()方法来释放锁,这样,设备就会在空闲的时候进行休眠来节省电池使用。

优化API——JobScheduler

在满足特定条件后,自动执行任务

用法如下代码

private void downloadSmarter() {

JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

// Beginning with 10 here to distinguish this activity's jobs from the

// FreeTheWakelockActivity's jobs within the JobScheduler API.

mServiceComponent = new ComponentName(this, MyJobService.class);

for (int i=10; i<20; i++) {

JobInfo jobInfo = new JobInfo.Builder(i, mServiceComponent)

.setMinimumLatency(5000) // 5 seconds

.setOverrideDeadline(60000) // 60 seconds (for brevity in the sample)

.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) // for Wifi only

.build();

mWifiMsg.append("Scheduling job " + i + "!\n");

scheduler.schedule(jobInfo);

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

privatevoiddownloadSmarter(){

JobSchedulerscheduler=(JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE);

// Beginning with 10 here to distinguish this activity's jobs from the

// FreeTheWakelockActivity's jobs within the JobScheduler API.

mServiceComponent=newComponentName(this,MyJobService.class);

for(inti=10;i<20;i++){

JobInfojobInfo=newJobInfo.Builder(i,mServiceComponent)

.setMinimumLatency(5000)// 5 seconds

.setOverrideDeadline(60000)// 60 seconds (for brevity in the sample)

.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)// for Wifi only

.build();

mWifiMsg.append("Scheduling job "+i+"!\n");

scheduler.schedule(jobInfo);

}

}

MyJobService 是我们自定义的继承自 JobService 的一个类,我们可以在其内部做一些处理,例如网络请求等等。

当满足特定条件时,这些job就会被调用,例子中使用的条件是,当wifi连接时。

要注意的是,这个api是在21以后才添加的。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐