利用广播监听手机解锁和锁屏的操作

时间:2022-01-08 19:01:39
##利用广播监听手机解锁、锁屏和亮屏的操作

public class MainActivity extends Activity {
BroadcastReceiver receiver;
private static String TAG = "MyLog";
private ScreenListener MyListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestBroadReceiver();
IntentFilter filter = new IntentFilter();//定义一个意图拦截
filter.addAction(Intent.ACTION_SCREEN_ON);//添加要拦截的动作
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(receiver, filter);//注册广播
}

public void TestBroadReceiver() {
receiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// TODO Auto-generated method stub
if (Intent.ACTION_SCREEN_ON.equals(action)) { // 开屏
//拦截事件后可在此操作
Log.i(TAG, "开屏");
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) { // 锁屏
//拦截事件后可在此操作
Log.i(TAG, "锁屏");
} else if (Intent.ACTION_USER_PRESENT.equals(action)) { // 解锁
//拦截事件后可在此操作
Log.i(TAG, "解锁");
}
}
};

}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);//销毁页面时注销广播
}
}