Android中获取亮屏状态和监听亮屏和灭屏事件

package com.xiboliya.demo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;

public class TestActivity extends Activity {
    private static final String TAG = TestActivity.class.getSimpleName();
    private ScreenReceiver mScreenReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_test);
        checkScreenStatus();
        registerScreenReceiver();
    }

    /**
     * 注册监听
     */
    private void registerScreenReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        mScreenReceiver = new ScreenReceiver();
        registerReceiver(mScreenReceiver, filter);
    }

    private void screenOn() {
        Log.d(TAG, "screen is on");
        // 亮屏状态下的代码逻辑
    }

    private void screenOff() {
        Log.d(TAG, "screen is off");
        // 灭屏状态下的代码逻辑
    }

    /**
     * 获取亮屏状态
     */
    private void checkScreenStatus() {
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = false;
        // Android 4.4W (KitKat Wear)系统及以上使用新接口获取亮屏状态
        if (Build.VERSION.SDK_INT >= 20) {
            isScreenOn = pm.isInteractive();
        } else {
            isScreenOn = pm.isScreenOn();
        }
        if (isScreenOn) {
            screenOn();
        } else {
            screenOff();
        }
    }

    /**
     * 监听亮屏和灭屏事件
     */
    private class ScreenReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_SCREEN_ON.equals(action)) {
                screenOn();
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                screenOff();
            }
        }
    }

}

你可能感兴趣的:(Android相关,android,PowerManager,亮屏灭屏)