Android Power optimization

Source: Internet
Author: User

The recent leadership has always reflected that our app consumes more power than before, in the first place in electricity consumption, on the blacklist, needs to be optimized! After a period of research, I did a part of the summary!

Power-Optimized tool Battery-historien

Battery-historien is Google's open source power detection and analysis tool, because many app developers are not so much attention to battery, star number is not very much!

Link: Https://github.com/google/battery-historian above has the concrete environment to build the step!

Environmental Building Steps

I'm using method two, and the steps are as follows:

1.下载go,安装,指定path路径2.下载python,安装,指定path3.下载git,安装4.下载Java,安装,指定path5.下载源码    go get -d -u github.com/google/battery-historian/…6.运行源码,下载依赖    cd $GOPATH/src/github.com/google/battery-historian    go run setup.go    发现下载不下来,手动下载closure-library,closure-compiler,flot-axislabels    分别解压到third_party下面7.运行监听    go run cmd/battery-historian/battery-historian.go    2017/04/16 18:23:02 Listening on port:  99998.检验运行情况    http://localhost:9999    2017/04/16 18:23:09 Trace starting analysisServer processing for: GET2017/04/16 18:23:09 Trace finished analysisServer processing for: GET
Export power files and analyze export files

The export file uses the ADB command to generate the file:

adb kill-serveradb start-server// 打开电池数据获取adb shell dumpsys batterystats --enable full-wake-history// 电池数据重置adb shell dumpsys batterystats --reset// 生成电量数据到文件adb bugreport > bugreport.txt
Analysis file:

There are two ways to parse a file:

Upload file analysis

One is to upload files to the server for analysis, but do not know what the reason, failed!
Open GUI bash in the Battery-historian directory, execute:

 go run cmd/battery-historian/battery-historian.gohistorian.py浏览器打开:http://localhost:9999/但是并没有什么卵用!生成的txt文件是无法上传进行分析的,可能是因为不兼容


After you choose the generated file, there is no post! It's sad! Decisive use of the second!

Converting to HTML file parsing

Use a Python script to parse, download the script to the appropriate directory

Use the command to generate the txt HTML file:

python historian.py -a bugreport.txt > battery.htmlWARNING: Visualizer disabled. If you see this message, download the HTML then open it.需要翻墙

Open the HTML file to see the power consumption:

Field analysis
plugged 充电状态top 那个app运行在最上面sync 跟后台同步wake_lock cpu的唤醒锁job 服务,后台任务runningconnectionwifimobile_ratio 蜂窝信号

Main power consumption places: screen light screen, cellular data (3g,4g), WIFI,CPU/GPU work, we need to pay special attention to these aspects!

Optimization strategy

Power optimization Strategy:
1. Charging for certain operations
Some do not need to interact with the user in a timely manner, can be put into charge and then proceed, such as picture processing after the photo, 360 mobile phone assistant after charging the phone automatically clean up
Spam, contact data upload to the cloud, etc...

监听电池充电操作    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);Intent batteryStatus = this.registerReceiver(null, filter);//几种充电方式:直流充电,USB充电,无线充电    int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);        boolean usbCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_USB);        boolean acCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC);        boolean wirelessCharge = false;        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {            wirelessCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS);        }        return (usbCharge || acCharge || wirelessCharge);    }

Operation in 2.WIFI state

    我们知道在蜂窝无线网络状态下会比WIFI状态下耗电的多,所以尽量减少移动网络下的数据传输,多在WIFI数据下操作!    //判断网络连接 private boolean isNetWorkConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return (activeNetworkInfo!=null&&activeNetworkInfo.isConnected()); }

3. Network Request Settings Timeout
When the network request, if the network is poor, the request takes a long time, we need to set the timeout time, reduce network consumption!

4. Task Focus Processing Jobscheduler
Use Jobscheduler to handle some specific operations

Jobscheduler Jobscheduler = (jobscheduler) getsystemservice (Context.job_scheduler_service); for(inti =0; I <Ten; i++) {Jobinfo Jobinfo =NewJobinfo.builder (I,componentname). Setminimumlatency (10000)//min. delay. Setoverridedeadline (60000)//Maximum execution time//. Setrequirednetworktype (jobinfo.network_type_unmetered)//Free network (wifi/bluetooth/USB), to fulfill this condition before going to execute. Setrequirednetworktype (Jobinfo.network_type_any)//any network---wifi. build ();        Jobscheduler.schedule (Jobinfo); }//Task handling Public  class jobservicetest extends jobservice {The disadvantage is that there is an API limit

A large number of centralized operations can be processed together
5.weak_lock cautious use
Weak_lock is mainly used to deal with the system sleep, we know that the system in order to save power generally after the screen to sleep, after hibernation all operations will be suspended Frozen (timer,services),
After hibernation, some background network access operations will be stopped, may lead to some problems, such as instant messaging heartbeat packets can not be issued in a timely manner, resulting in the receipt of messages,
To prevent these situations, you need to use Weak_lock to wake up the CPU, right with our program execution!

wake_lock:两种锁,一种计数锁(锁一次,释放一次);非计数锁(锁了很多次,只需要release一次就可以解除了

Using Weak_lock:

//Registration rights<Uses-permissionAndroid:name="Android.permission.INTERNET"></uses-permission>    <Uses-permissionAndroid:name="Android.permission.WAKE_LOCK"></uses-permission>    <Uses-permissionAndroid:name="Android.permission.ACCESS_NETWORK_STATE"></uses-permission>PowerManager PowerManager=(PowerManager) Getsystemservice (Power_service); WakeLock WakeLock=PowerManager.Newwakelock (PowerManager.Partial_wake_lock,"Mywakelocktag"); Mwakelock.Acquire ();//wake-up CPUMwakelock.Release ();//Release CPU lockNote: When using this class, you must ensure that acquire and release are paired.
Need to be aware

1. Wake Up CPU Frequency

唤醒CPU的频率也不能太高,不然可能会出现一些问题,比如小米手机做了同步心跳(心跳对齐),如果超出了这个心跳的频率,就会被屏蔽或者降频!

2. Using Alarmmanager
Alarmmanager is the system's alarm clock service, can be used to wake up the CPU, do some background tasks, even after the screen is out of normal work (scheduled tasks do not use timer, Handler, Thread, Service)

Intent intent = new Intent(context, Service.class);PendingIntent pi = PendingIntent.getService(context, 1, intent, 0);AlarmManager alarm = (AlarmManager) getSystemService(Service.ALARM_SERVICE);if(alarm != null){    alarm.cancel(pi);    // 闹钟在系统睡眠状态下会唤醒系统并执行提示功能    alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, 2000, pi);// 确切的时间闹钟//alarm.setExact(…);    //alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);}

3. Keep the screen constant
After the screen shuts down, the system sleeps, some tasks may be paused (Timer, Handler, Thread, Service), but in some cases we need to keep the screen constant, or we don't need the screen constants but need the CPU to execute until the task is done. Then we can manually set the screen to solid!

//在Acitivty里面使用FlaggetWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);FLAG_KEEP_SCREEN_ON的好处是使用方便,不要额外的权限!

Android Power optimization

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.