PowerManager管理亮灭屏操作

    /* 注册监听亮灭屏广播,当灭屏时,点亮屏幕 */
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "action = " + intent.getAction());
            if (Intent.ACTION_SCREEN_ON.equalsIgnoreCase(intent.getAction())) {
                Log.d(TAG, "screen on.");
                mScreenOnTxt.setText("screen on");
            } else if (Intent.ACTION_SCREEN_OFF.equalsIgnoreCase(intent.getAction())) {
                Log.d(TAG, "screen off");
                mScreenOnTxt.setText("screen off");
                wakeUpScreen();
            }
        }
    };

    private void registerScreenOnReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mBroadcastReceiver, filter);
    }

    private void wakeUpScreen() {
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (mWakeLock == null) {
            mWakeLock = powerManager.newWakeLock(
                PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,
                "MainActivity:wakeup");
        }
        /* 如果屏幕亮屏状态,就不再点亮 */
        if (powerManager.isScreenOn()) {
            return;
        }
        if (mWakeLock.isHeld()) {
            mWakeLock.release();  //需要释放锁,调用acquire点亮屏幕
        }
        mWakeLock.acquire();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
        if (mWakeLock != null && mWakeLock.isHeld()) {
            mWakeLock.release();
        }
    }

wakelock几种亮屏类型定义:

类型  cpu 屏幕 键盘
PARTIAL_WAKE_LOCK on off off
SCREEN_DIM_WAKE_LOCK on dim off
SCREEN_BRIGHT_WAKE_LOCK on Brigh off
FULL_WAKE_LOCK on Brigh Brigh

 

 

 

 

你可能感兴趣的:(android,手机亮灭屏)