PowerManager和WakeLock的操作步驟

PowerManager和WakeLock的操作步驟

 

轉自:http://www.cnblogs.com/GnagWang/archive/2011/02/27/1966611.html

  1. PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);通過 Context.getSystemService().方法獲取PowerManager實例。
  2. 然後通過PowerManager的newWakeLock((int flags, String tag)來生成WakeLock實例。int Flags指示要獲取哪種WakeLock,不同的Lock對cpu 、屏幕、鍵盤燈有不同影響。
  3. 獲取WakeLock實例後通過acquire()獲取相應的鎖,然後進行其他業務邏輯的操作,最後使用release()釋放(釋放是必須的)。
  4. WakeLock.acquire(); //喚醒點亮屏幕

    //這個期間屏幕將點亮

    WakeLock.release(); //恢復屏幕到黑暗

    當然Android考慮到安全並不是說開發者有了權限,就可以隨意的控制屏幕的背光顯示或無,只有通過acquire點亮的背光才能使用release讓其關閉背光,如果直接調用release方法關閉屏幕將會產生一個異常。

    從Android 2.1 API Level7開始增加了一個判斷屏幕是否處於點亮狀態可以使用public boolean isScreenOn ()這個方法,代碼爲

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    boolean isScreenOn = pm.isScreenOn();

關於int flags

各種鎖的類型對CPU 、屏幕、鍵盤的影響:

PARTIAL_WAKE_LOCK:保持CPU 運轉,屏幕和鍵盤燈有可能是關閉的。

SCREEN_DIM_WAKE_LOCK:保持CPU 運轉,允許保持屏幕顯示但有可能是灰的,允許關閉鍵盤燈

SCREEN_BRIGHT_WAKE_LOCK:保持CPU 運轉,允許保持屏幕高亮顯示,允許關閉鍵盤燈

FULL_WAKE_LOCK:保持CPU 運轉,保持屏幕高亮顯示,鍵盤燈也保持亮度

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.

權限獲取

要進行電源的操作需要在AndroidManifest.xml中聲明該應用有設置電源管理的權限。

<uses-permission android:name="android.permission.WAKE_LOCK" /> 你可能還需要 <uses-permission android:name="android.permission.DEVICE_POWER" />

另外WakeLock的設置是 Activiy 級別的,不是針對整個Application應用的。

可以在activity的onResume方法裏面操作WakeLock, 在onPause方法裏面釋放。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章