目录
- java版
- kotlin版本
java版
不需要xml代码,直接java代码注册就好。
public class MainActivity extends AppCompatActivity {private static final String TAG = "MainActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);final IntentFilter filter = new IntentFilter();// 屏幕灭屏广播filter.addAction(Intent.ACTION_SCREEN_OFF);// 屏幕亮屏广播filter.addAction(Intent.ACTION_SCREEN_ON);BroadcastReceiver mScreenInfoReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(final Context context, final Intent intent) {Log.d(TAG, "onReceive");String action = intent.getAction();if (Intent.ACTION_SCREEN_ON.equals(action)) {Log.d(TAG, "screen on");} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {Log.d(TAG, "screen off");}}};registerReceiver(mScreenInfoReceiver, filter);}
}
按锁屏键,测试效果:
kotlin版本
class MainActivity : AppCompatActivity() {companion object {private const val TAG = "MainActivity"}class ScreenReceiver : BroadcastReceiver() {override fun onReceive(context: Context, intent: Intent) {Log.d(TAG, "onReceive: ")var action = intent.getAction()if (Intent.ACTION_SCREEN_ON.equals(action)) {Log.d(TAG, "screen on")} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {Log.d(TAG, "screen off")}}}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val filter = IntentFilter()filter.addAction(Intent.ACTION_SCREEN_OFF)filter.addAction(Intent.ACTION_SCREEN_ON)var receiver = ScreenReceiver()registerReceiver(receiver, filter)}
}
按锁屏键,测试效果: