Android PowerManager 之一 初識

綜述

PowerManager 類主要對當前設備的電源進行管理;通過改API的使用,我們可以顯示的獲得對電源的控制權,換句話說,設備電池的電量必然會收到顯著的影響。通常情況下,不建議直接使用PowerManager.WakeLock,即便是使用也要遵循最小粒度原則並且及時的釋放申請的WakeLock

使用

可以通過Context.getSystemServie()來獲得PowerManager的實例;常用的API其實是newWakeLocknewWakeLock用於創建PowerManager.WakeLock對象;我們可以通過WakeLock對象相關方法來對設備電源進行控制。常見的代碼如下所示:

PowerManager pm = (PowerManager)
getSystemService(Context.POWER_SERVICE);
 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
 wl.acquire();
   //..screen will stay on during this section..
 wl.release();

級別

PowerManager定義瞭如下級別,與之對應的就是不同的電源控制全;這些級別都是互斥的,同一時刻只能使用一種

Flag Value CPU Screen Keyboard
PARTIAL_WAKE_LOCK On* Off Off
SCREEN_DIM_WAKE_LOCK On Dim Off
SCREEN_BRIGHT_WAKE_LOCK Bright Off
FULL_WAKE_LOCK On Bright Off

在申請了PARTIAL_WAKE_LOCK 的wake lock之後,此時不論設備設置的timeout是多少,或者屏幕手動的使用power按鍵滅屏,CPU都會處於運行狀態。項對比其他類型的wake lock而言,可以通過power按鍵讓設備進入到休眠模式。

通常情況下,我們可以講如下的flag同wake lock搭配使用已達到控制屏幕、控制何時休眠的目的PARTIAL_WAKE_LOCK除外

Flag Value Description
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 If 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.

當然要想使用WakeLock還得有權限android.permission.WAKE_LOCK

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