移動開發----Android判斷螢幕鎖屏的方法
阿新 • • 發佈:2018-12-13
由於做一個專案,需要判斷螢幕是否鎖屏,發現網上方法很多,但是比較雜,現在進行總結一下: 總共有兩類方法: 一、程式碼直接判定 二、接收廣播 現在先說第一類方法(程式碼直接判定): 1、通過PowerManager的isScreenOn方法,程式碼如下: [java] view plain copy 在CODE上檢視程式碼片派生到我的程式碼片 PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); boolean isScreenOn = pm.isScreenOn();//如果為true,則表示螢幕“亮”了,否則螢幕“暗”了。 註釋已經寫的很明白了,現在大概說一下, 螢幕“亮”,表示有兩種狀態:a、未鎖屏 b、目前正處於解鎖狀態 。這兩種狀態螢幕都是亮的 螢幕“暗”,表示目前螢幕是黑的 。 2、通過KeyguardManager的inKeyguardRestrictedInputMode方法,程式碼如下: [java] view plain copy 在CODE上檢視程式碼片派生到我的程式碼片 KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode(); 註釋已經寫的很明白了,現在大概說一下,boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode(); 原始碼的返回值的解釋是:true if in keyguard restricted input mode. 經過試驗,總結為: 如果flag為true,表示有兩種狀態:a、螢幕是黑的 b、目前正處於解鎖狀態 。 如果flag為false,表示目前未鎖屏 註明:上面的兩種方法,也可以通過反射機制來呼叫。 下面以第一個方法為例說明一下。 [java] view plain copy 在CODE上檢視程式碼片派生到我的程式碼片 private static Method mReflectScreenState; try { mReflectScreenState = PowerManager.class.getMethod("isScreenOn", new Class[] {}); PowerManager pm = (PowerManager) context.getSystemService(Activity.POWER_SERVICE); boolean isScreenOn= (Boolean) mReflectScreenState.invoke(pm); } catch (Exception e) { e.printStackTrace() } 現在介紹第二類方法(接收系統的廣播): 接收系統廣播事件,螢幕在三種狀態(開屏、鎖屏、解鎖)之間變換的時候,系統都會發送廣播,我們只需要監聽這些廣播即可。 程式碼如下: [java] view plain copy 在CODE上檢視程式碼片派生到我的程式碼片 private ScreenBroadcastReceiver mScreenReceiver; 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)) { // 開屏 } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { // 鎖屏 } else if (Intent.ACTION_USER_PRESENT.equals(action)) { // 解鎖 } } } private void startScreenBroadcastReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); context.registerReceiver(mScreenReceiver, filter); } 好了,就寫這麼多了,希望對大家有用!!