1、首先定义ScreenListener
package com.app.lib;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.os.PowerManager;/*** Created by ${zyj} on /6/21.*/public class ScreenListener {private Context mContext;private ScreenBroadcastReceiver mScreenReceiver;private ScreenStateListener mScreenStateListener;public ScreenListener(Context context) {mContext = context;mScreenReceiver = new ScreenBroadcastReceiver();}/*** screen状态广播接收者*/private class ScreenBroadcastReceiver extends BroadcastReceiver {private String action = null;@Overridepublic void onReceive(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状态** @param listener*/public void begin(ScreenStateListener listener) {mScreenStateListener = listener;registerListener();getScreenState();}/*** 获取screen状态*/private void getScreenState() {PowerManager manager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);if (manager.isScreenOn()) {if (mScreenStateListener != null) {mScreenStateListener.onScreenOn();}} else {if (mScreenStateListener != null) {mScreenStateListener.onScreenOff();}}}/*** 停止screen状态监听*/public void unregisterListener() {mContext.unregisterReceiver(mScreenReceiver);}/*** 启动screen状态广播接收器*/private void registerListener() {IntentFilter filter = new IntentFilter();filter.addAction(Intent.ACTION_SCREEN_ON);filter.addAction(Intent.ACTION_SCREEN_OFF);filter.addAction(Intent.ACTION_USER_PRESENT);mContext.registerReceiver(mScreenReceiver, filter);}public interface ScreenStateListener {// 返回给调用者屏幕状态信息public void onScreenOn();public void onScreenOff();public void onUserPresent();}}
2.使用
package com.app.lib;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast;public class MainActivity extends AppCompatActivity {private ScreenListener screenListener ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);screenListener = new ScreenListener( MainActivity.this ) ;screenListener.begin(new ScreenListener.ScreenStateListener() {@Overridepublic void onScreenOn() {Toast.makeText( MainActivity.this , "屏幕打开了" , Toast.LENGTH_SHORT ).show();}@Overridepublic void onScreenOff() {Toast.makeText( MainActivity.this , "屏幕关闭了" , Toast.LENGTH_SHORT ).show();}@Overridepublic void onUserPresent() {Toast.makeText( MainActivity.this , "解锁了" , Toast.LENGTH_SHORT ).show();}});}}
郑重声明:本文转载自:/zhaoyanjun
原文链接:/zhaoyanjun/p/5614592.html
更多干货文章,请扫描二维码订阅哦:
您可以扫描上面的二维码,来关注我的微信公众号,来学习更多的干货文章!
另外,我还建了一个免费的知识星球,感兴趣的微信扫码即可加入!
如果觉得《Android监听屏幕锁屏》对你有帮助,请点赞、收藏,并留下你的观点哦!