android 手机监听屏幕锁屏,用户解锁

用到的场景很多,自己发挥 ,废话不多说直接上代码:

private classScreenBroadcastReceiverextendsBroadcastReceiver{

privateStringaction= null;

@Override

public voidonReceive(Context context,Intent intent) {

        action=intent.getAction();

        if(Intent.ACTION_SCREEN_ON.equals(action)) {// 开屏

                              mScreenStateListener.onScreenOn();

        }else if(Intent.ACTION_SCREEN_OFF.equals(action)) {// 锁屏

                             mScreenStateListener.onScreenOff();

        }else if(Intent.ACTION_USER_PRESENT.equals(action)) {// 解锁

                              mScreenStateListener.onUserPresent();

        }

  }

}

/**

* 开始监听screen状态

*

* @paramlistener

*/

public voidbegin(ScreenStateListener listener) {

                                 mScreenStateListener=listener;

                                 registerListener();

                                 getScreenState();

}

/**

* 获取screen状态

*/

private voidgetScreenState() {

     PowerManagermanager=(PowerManager)mContext.getSystemService(Context.POWER_SERVICE);

     if(manager.isScreenOn()) {

                if(mScreenStateListener!= null) {

                         mScreenStateListener.onScreenOn();

               }

     }else{

                if(mScreenStateListener!= null) {

                        mScreenStateListener.onScreenOff();

                 }

     }

}

/**

* 停止screen状态监听

*/

public voidunregisterListener() {

            mContext.unregisterReceiver(mScreenReceiver);

}

/**

* 启动screen状态广播接收器

*/

private voidregisterListener() {

        IntentFilterfilter= newIntentFilter();

        filter.addAction(Intent.ACTION_SCREEN_ON);

        filter.addAction(Intent.ACTION_SCREEN_OFF);

        filter.addAction(Intent.ACTION_USER_PRESENT);

        mContext.registerReceiver(mScreenReceiver,filter);

}

public interfaceScreenStateListener{// 返回给调用者屏幕状态信息

          public voidonScreenOn();

          public voidonScreenOff();

          public voidonUserPresent();

    }

}

在上面的代码中,用到了动态注册广播,在需要监听屏幕状态的activity中直接调用,当不需要监听的时候,如activity finish的时候,使用unregisterListener解除广播监听;

下面是在Activity中调用;


ScreenListener screenListener = new ScreenListener(this) ; 

screenListener.begin(new ScreenListener.ScreenStateListener() {

@Override

public void onScreenOn() {

                Toast.makeText( CounterTActivity.this , "屏幕打开了" , Toast.LENGTH_SHORT ).show();

}

@Override

public void onScreenOff() {

                Toast.makeText( CounterTActivity.this , "屏幕关闭了" , Toast.LENGTH_SHORT ).show();

}

@Override

public void onUserPresent() {

                Toast.makeText( CounterTActivity.this , "解锁了" , Toast.LENGTH_SHORT ).show();

}

});

你可能感兴趣的:(android 手机监听屏幕锁屏,用户解锁)