有些情境需要程式自動點亮螢幕,解開螢幕鎖,以方便使用者即時操作,下面用代碼來實現這一功能:
- //得到鍵盤鎖管理器對象
- KeyguardManager km= (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
- //參數是LogCat裡用的Tag
- KeyguardLock kl = km.newKeyguardLock("unLock");
- //解鎖
- kl.disableKeyguard();
- //擷取電源管理器對象
- PowerManager pm=(PowerManager) getSystemService(Context.POWER_SERVICE);
- //擷取PowerManager.WakeLock對象,後面的參數|表示同時傳入兩個值,最後的是LogCat裡用的Tag
- PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
- //點亮螢幕
- wl.acquire();
- //釋放
- wl.release();
需要在AndroidManifest.xml添加許可權:
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
flags參數說明:
- PARTIAL_WAKE_LOCK: Screen off, keyboard light off
- SCREEN_DIM_WAKE_LOCK: screen dim, keyboard light off
- SCREEN_BRIGHT_WAKE_LOCK: screen bright, keyboard light off
- FULL_WAKE_LOCK: screen bright, keyboard bright
ACQUIRE_CAUSES_WAKEUP:Normal wake locks don't actually turn on the illumination. Instead, they cause the illumination to remain on once it turns on (e.g. from user activity). This flag will force the screen and/or keyboard to turn on immediately,
when the WakeLock is acquired. A typical use would be for notifications which are important for the user to see immediately.
ON_AFTER_RELEASE:f this flag is set, the user activity timer will be reset when the WakeLock is released, causing the illumination to remain on a bit longer. This can be used to reduce flicker if you are cycling between wake lock conditions.