MENU

Android WakeLock版本坑

June 22, 2018 • Android

今天发现之前用的这个方法

 val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
 pm.newWakeLock(FLAG_KEEP_SCREEN_ON, "KEEP")

在6.0以下的机子会报错,报了如下错误

Must specify a valid wake lock level.

去看了源码:

public WakeLock newWakeLock(int levelAndFlags, String tag) {
        validateWakeLockParameters(levelAndFlags, tag);
        return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
    }

    /** @hide */
public static void validateWakeLockParameters(int levelAndFlags, String tag) {
        switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
            case PARTIAL_WAKE_LOCK:
            case SCREEN_DIM_WAKE_LOCK:
            case SCREEN_BRIGHT_WAKE_LOCK:
            case FULL_WAKE_LOCK:
            case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
            case DOZE_WAKE_LOCK:
            case DRAW_WAKE_LOCK:
                break;
            default:
                throw new IllegalArgumentException("Must specify a valid wake lock level.");
        }
        if (tag == null) {
            throw new IllegalArgumentException("The tag must not be null.");
        }
    }

然后再看了一下,发现case的这些常量都是废弃的,注释中推荐让我使用文章开头的那个常量

/**
     * Wake lock level: Ensures that the screen and keyboard backlight are on at
     * full brightness.
     * <p>
     * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be
     * implicitly released by the system, causing both the screen and the CPU to be turned off.
     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
     * </p>
     *
     * @deprecated Most applications should use
     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
     * of this type of wake lock, as it will be correctly managed by the platform
     * as the user moves between applications and doesn't require a special permission.
     */
    @Deprecated
    public static final int FULL_WAKE_LOCK = 0x0000001a;

然后又绕了一圈,最终使用版本判断来解决这个问题

val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
mWakeLock = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
         pm.newWakeLock(SCREEN_DIM_WAKE_LOCK, "KEEP")
        } else {
         pm.newWakeLock(FLAG_KEEP_SCREEN_ON, "KEEP")
        }
Archives QR Code
QR Code for this page
Tipping QR Code