Android画面のロック解除と点灯


一部のシーンでは、ユーザーの即時操作を容易にするために、プログラムが自動的にスクリーンを点灯し、スクリーンロックを解除する必要があります.以下、コードでこの機能を実現します.

  
  
  
  
  1. 1.//      
  2. 2.KeyguardManager  km= (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);     
  3. 3.// LogCat Tag     
  4. 4.KeyguardLock kl = km.newKeyguardLock("unLock");     
  5. 5.//      
  6. 6.kl.disableKeyguard();     
  7. 7.    
  8. 8.//      
  9. 9.PowerManager pm=(PowerManager) getSystemService(Context.POWER_SERVICE);     
  10. 10.// PowerManager.WakeLock , | , LogCat Tag     
  11. 11.PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");     
  12. 12.//      
  13. 13.wl.acquire();     
  14. 14.//      
  15. 15.wl.release();    

AndroidManifestでxml権限の追加:

  
  
  
  
  1. <uses-permission android:name="android.permission.WAKE_LOCK" /> 
  2.    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> 

flagsパラメータの説明:

  
  
  
  
  1. PARTIAL_WAKE_LOCK: Screen off, keyboard light off
  2. SCREEN_DIM_WAKE_LOCK: screen dim, keyboard light off
  3. SCREEN_BRIGHT_WAKE_LOCK: screen bright, keyboard light off
  4. 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.
 
2、画面の起動を維持use the window flag FLAG_KEEP_SCREEN_ON次のコードをプログラムonCreateメソッドに追加

  
  
  
  
  1. @Override 
  2. protected void onCreate(Bundle icicle) {  
  3. super.onCreate(icicle);  
  4. // Set keep screen on  
  5.  
  6. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
  7. }