计算机技术实战

纸上得来终觉浅,绝知此事要躬行。

Download this project as a .zip file Download this project as a tar.gz file

电池寿命

参考文档

https://developer.android.com/topic/performance/power/

省电主要思想

电量问题分析

官方文档

  1. https://developer.android.com/topic/performance/power/battery-historian
  2. https://github.com/google/battery-historian

注意官方Github文档关于docker的命令需要改动才能运行:

docker run -p 8812:9999 gcr.io/android-battery-historian/stable:3.0 --port 9999

成功之后,浏览器输入:http://localhost:8812/

命令行输入:

adb bugreport bugreport.zip

成功之后会在PC本地生成bugreport.zip文件,打开http://localhost:8812/,上传bugreport.zip文件,上传完成之后应该是这个界面:

从报表中可以看到电量使用的场景,例如有几个Service在耗电:

可以使用命令清除历史数据,重新统计:

adb shell dumpsys batterystats --reset

电量优化策略

        /**
         * Specify that to run this job, the device needs to be plugged in. This defaults to
         * false.
         * @param requiresCharging Whether or not the device is plugged in.
         */
        public Builder setRequiresCharging(boolean requiresCharging) {
            mConstraintFlags = (mConstraintFlags&~CONSTRAINT_FLAG_CHARGING)
                    | (requiresCharging ? CONSTRAINT_FLAG_CHARGING : 0);
            return this;
        }

禁止收听静态注册广播,注意这个会一直生效,需要注意启用。

        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(
                new ComponentName(this, MyBroadCastReceiver.class),
                isChecked ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                        : PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

注册/取消注册动态广播

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

可以使用adb命令模拟广播发送,更多命令参考:https://developer.android.com/studio/command-line/adb

adb shell am broadcast -a com.github.mwping.broadcastnotify