public class MainActivity extends AppCompatActivity {
private ScreenReceiver screenReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//动态的去注册广播接收者
screenReceiver = new ScreenReceiver();
//创建IntentFilter对象
IntentFilter filter = new IntentFilter();
//添加要注册的action
filter.addAction("android.intent.action.SCREEN_OFF");
filter.addAction("android.intent.action.SCREEN_ON");
//动态注册广播接收者
registerReceiver(screenReceiver, filter);
}
@Override
protected void onDestroy() {
//当activity销毁的时候要取消注册广播接收者
unregisterReceiver(screenReceiver);
super.onDestroy();
}
}
public class ScreenReceiver extends BroadcastReceiver {
//当我们进行屏幕锁屏和解锁时 这个方法执行
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// throw new UnsupportedOperationException("Not yet implemented");
//获取当前广播的事件类型
String action = intent.getAction();
if ("android.intent.action.SCREEN_OFF".equals(action)) {
Log.d("jojo", "onReceive: 屏幕锁屏了");
} else if ("android.intent.action.SCREEN_ON".equals(action)) {
Log.d("jojo", "onReceive: 屏幕解锁了");
}
}
}