Highly recommended article: Welcome to collect Android dry goods to share

##### Read five minutes, 10 o ‘clock every day, and learn for life with you. This is Android programmer

Battery optimization has always been a top issue in Android development. This article will analyze some knowledge points related to power optimization measures above Android M.

Note: This article refers to the MTK mobile solution documentation

Here’s what you’ll learn from this article:

Doze mode 2. Optimize app power consumption in idle state 3. Restrictions in Doze mode 4. Enable the Doze Dubug debugging

1. The Doze mode

When the device is stationary for a period of time under the non-charging and off-screen state, the device will enter the sleep state and enter the Doze mode to extend the battery life. In Doze mode, the system will resume normal operation periodically and asynchronously perform some data synchronization operations of app. For example, if the device is not used for a long time, the system allows the device to access the network once a day. When the device is in charge state, the system will enter the standard mode, and the APP will not be restricted to perform operations.

2. Optimize app power consumption in idle state

If the user does not use the APP, the system will make the app in idle state. In idle state, the system will prohibit the app network access and data synchronization

3. Restrictions in Doze mode

1) prohibit Internet access (2) ignore the Wake lock 3. Ignore the Alarms (setAlarmClock (), AlarmManager. SetAndAllowwhileIdle () these two methods except) 4. Ignore WIFI scan 5. Synchronous job scheduler will not be executed

4. Outline of Doze Mode

5. Classes involved in Doze mode are as follows:

frameworks/base/services/core/java/com/android/server/DeviceIdleController.java

   /**
  * Keeps track of device idleness and drives low power mode based on that.
  */
   public class DeviceIdleController extends SystemService
        implements AnyMotionDetector.DeviceIdleCallback {
Copy the code

6. Doze mode

  • ACTIVE: The mobile device is in ACTIVE state
  • INACTIVE: The screen closes and enters the INACTIVE state
  • IDLE_PENDING: Put your App into a pending state every 30 minutes
  • IDLE: indicates the IDLE state
  • IDLE_MAINTENANCE: Handles pending tasks

The corresponding Doze mode states are as follows:

active—> inactive —> idle_pending

Motion pattern detection

  void handleMotionDetectedLocked(long timeout, String type) {
        // The device is not yet active, so we want to go back to the pending idle
        // state to wait again for no motion.  Note that we only monitor for motion
        // after moving out of the inactive state, so no need to worry about that.
        boolean becomeInactive = false;
        if(mState ! = STATE_ACTIVE) { scheduleReportActiveLocked(type, Process.myUid());
            mState = STATE_ACTIVE;
            mInactiveTimeout = timeout;
            mCurIdleBudget = 0;
            mMaintenanceStartTime = 0;
            EventLogTags.writeDeviceIdle(mState, type);
            addEvent(EVENT_NORMAL);
            becomeInactive = true;
        }
        if (mLightState == LIGHT_STATE_OVERRIDE) {
            // We went out of light idle mode because we had started deep idle mode...  let's // now go back and reset things so we resume light idling if appropriate. mLightState = STATE_ACTIVE; EventLogTags.writeDeviceIdleLight(mLightState, type); becomeInactive = true; } if (becomeInactive) { becomeInactiveIfAppropriateLocked(); }}Copy the code

Idle_pending — – > sensing


    @Override
    public void onAnyMotionResult(int result) {
        if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
        if (result != AnyMotionDetector.RESULT_UNKNOWN) {
            synchronized (this) {
                cancelSensingTimeoutAlarmLocked();
            }
        }
        if (result == AnyMotionDetector.RESULT_MOVED) {
            if (DEBUG) Slog.d(TAG, "RESULT_MOVED received.");
            synchronized (this) {
                handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "sense_motion"); }}else if (result == AnyMotionDetector.RESULT_STATIONARY) {
            if (DEBUG) Slog.d(TAG, "RESULT_STATIONARY received.");
            if (mState == STATE_SENSING) {
                // If we are currently sensing, it is time to move to locating.
                synchronized (this) {
                    mNotMoving = true;
                    stepIdleStateLocked("s:stationary"); }}else if (mState == STATE_LOCATING) {
                // If we are currently locating, note that we are not moving and step
                // if we have located the position.
                synchronized (this) {
                    mNotMoving = true;
                    if (mLocated) {
                        stepIdleStateLocked("s:stationary");
                    }
                }
            }
        }
    }
Copy the code

7. Doze white list

Battery Optimization Whitelist Setting — Battery optimization (Menu menu) Will set view app battery optimization usage whitelist stored in XML form (deviceidle.xml) View whitelist command

Adb shell Dumpsys Deviceidle Whitelist adb shell Dumpsys Deviceidle WhitelistCopy the code

Whitelist code save part of the code below


    /**
     * Package names the system has white-listed to opt out of power save restrictions,
     * except for device idle mode.
     */
    private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();

    /**
     * Package names the system has white-listed to opt out of power save restrictions for
     * all modes.
     */
    private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();

    /**
     * Package names the user has white-listed to opt out of power save restrictions.
     */
    private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();

    /**
     * App IDs of built-in system apps that have been white-listed except for idle modes.
     */
    private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
            = new SparseBooleanArray();

    /**
     * App IDs of built-in system apps that have been white-listed.
     */
    private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();

    /**
     * App IDs that have been white-listed to opt out of power save restrictions, except
     * for device idle modes.
     */
    private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();

    /**
     * Current app IDs that are in the complete power save white list, but shouldn't be * excluded from idle modes. This array can be shared with others because it will not be * modified once set. */ private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0]; /** * App IDs that have been white-listed to opt out of power save restrictions. */ private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray(); /** * Current app IDs that are in the complete power save white list. This array can * be shared with others because it will not be modified once set. */ private int[] mPowerSaveWhitelistAllAppIdArray = new int[0]; /** * App IDs that have been white-listed by the user to opt out of power save restrictions. */ private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray(); /** * Current app IDs that are in the user power save white list. This array can * be shared with others because it will  not be modified once set. */ private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];Copy the code

8. Doze mode test method

1. Open the Doze adb shell dumpsys deviceidle enable / / or MTK addadb shell setprop persist. Config. AutoPowerModes 1 2. Adb shell Dumpsys Battery unplug 3. Debug Doze status

Active ---idle_pending---sensing--location---idle --idle_mantenance

Adb shell Dumpsys Deviceidle step 4

Adb shell Dumpsys Deviceidle ##9 adb Shell Dumpsys Deviceidle Enable the Doze Dubug debugging

The default false closed and open DeviceIdleController is set to true. Java private static final Boolean DEBUG = false;

At this point, this has ended, if there is wrong place, welcome your suggestion and correction. Meanwhile, I look forward to your attention. Thank you for reading. Thank you!