package com.lidaochen.test001; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; 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); } }
package com.lidaochen.test001; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class ScreenReceiver extends BroadcastReceiver { // 当我们进行屏幕锁屏和解锁时,执行下面的方法 @Override public void onReceive(Context context, Intent intent) { // 获取当前广播的事件类型 String action = intent.getAction(); if("android.intent.action.SCREEN_OFF".equals(action)) { System.out.println("锁屏!"); Log.e("screen","锁屏"); } else if("android.intent.action.SCREEN_ON".equals(action)) { System.out.println("解锁!"); Log.e("screen","解锁"); } } }