Android锁屏及监听锁屏事件

/** * 获得锁屏时间 毫秒 */private int getScreenOffTime() {int screenOffTime = 0;try {screenOffTime = Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT);} catch (Exception e) {Log.e("albert988", e.toString());}return screenOffTime ;}

调用系统的设置,获取到当前设置的锁屏时间,单位为毫秒


/** * 设置锁屏时间 */private boolean setScreenOffTime(int paramInt){try {// 写入系统设置中Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, paramInt);} catch (Exception e) {Log.e("albert988", e.toString());return false;}return true;}

如要设置,得添加上


 此类作监听屏幕的ON和OFF状态事件
 构造时启动ScreenBroadcastReceiver来截取屏幕的广播
 当结束时别忘了调用stopScreenStateUpdate来取消注册广播 

/** * 监听屏幕ON和OFF状态 * * @author hejinyuan * @2012 * */public class ScreenObserver{private static String TAG = "ScreenObserver";private Context mContext;private ScreenBroadcastReceiver mScreenReceiver;    private ScreenStateListener mScreenStateListener;    private static Method mReflectScreenState;    public ScreenObserver(Context context){mContext = context;mScreenReceiver = new ScreenBroadcastReceiver();try {mReflectScreenState = PowerManager.class.getMethod("isScreenOn",new Class[] {});} catch (NoSuchMethodException nsme) {Log.d(TAG, "API < 7," + nsme);}}/**     * screen状态广播接收者     */    private class ScreenBroadcastReceiver extends BroadcastReceiver{    @Override    public void onReceive(Context context, Intent intent) {    if(Intent.ACTION_SCREEN_ON.equals(intent.getAction())){    mScreenStateListener.onScreenOn();    }else if(Intent.ACTION_SCREEN_OFF.equals(intent.getAction())){    mScreenStateListener.onScreenOff();    }    }    }/** * 请求screen状态更新 */public void requestScreenStateUpdate(ScreenStateListener listener) {mScreenStateListener = listener;startScreenBroadcastReceiver();firstGetScreenState();}/** * 第一次请求screen状态 */private void firstGetScreenState(){PowerManager manager = (PowerManager) mContext.getSystemService(Activity.POWER_SERVICE);if (isScreenOn(manager)) {if (mScreenStateListener != null) {mScreenStateListener.onScreenOn();}} else {if (mScreenStateListener != null) {mScreenStateListener.onScreenOff();}}}/** * 停止screen状态更新 */public void stopScreenStateUpdate(){mContext.unregisterReceiver(mScreenReceiver);}/** * 启动screen状态广播接收器 */    private void startScreenBroadcastReceiver(){    IntentFilter filter = new IntentFilter();    filter.addAction(Intent.ACTION_SCREEN_ON);    filter.addAction(Intent.ACTION_SCREEN_OFF);    mContext.registerReceiver(mScreenReceiver, filter);    }    /**     * screen是否打开状态     */private static boolean isScreenOn(PowerManager pm) {boolean screenState;try {screenState = (Boolean) mReflectScreenState.invoke(pm);} catch (Exception e) {screenState = false;}return screenState;}// 外部调用接口public interface ScreenStateListener {public void onScreenOn();public void onScreenOff();}}