Android 監聽屏幕鎖屏&用戶解鎖
阿新 • • 發佈:2018-08-24
clas 開始 ets adc spa contex screen context scree 在做視頻播放器的時候,遇到一個問題,在用戶播放視頻然後鎖屏之後,視頻播放器仍然在繼續播放,遇到類似手機系統狀態改變的問題的時候,首先想到了廣播,下面做個總結:
public class ScreenListener { private Context mContext; private ScreenBroadcastReceiver mScreenReceiver; private ScreenStateListener mScreenStateListener; public ScreenListener(Context context) { mContext在上面的代碼中,用到了動態註冊廣播,在需要監聽屏幕狀態的activity中,當不需要監聽的時候,如activity finish的時候,使用unregisterListener解除廣播監聽; 下面是在Activity中調用;= context; mScreenReceiver = new ScreenBroadcastReceiver(); } /** * screen狀態廣播接收者 */ private class ScreenBroadcastReceiver extends BroadcastReceiver { private String action = null; @Override public 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(); } }
ScreenListener l = new ScreenListener(this); l.begin(new ScreenStateListener() { @Override public void onUserPresent() { Log.e("onUserPresent", "onUserPresent"); } @Override public void onScreenOn() { Log.e("onScreenOn", "onScreenOn"); } @Override public void onScreenOff() { Log.e("onScreenOff", "onScreenOff"); } });通過以上步驟即實現了對屏幕狀態的監聽.
Android 監聽屏幕鎖屏&用戶解鎖