天天看點

PowerManager 電源管理

PowerManager 電源管理

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);通過 context.getSystemService()擷取PowerManager執行個體。注意:對電源的設定是Activity級别的,不同的activity可以有不同的設定,這裡的Context是Activity的,不是ApplicationContext.

然後通過PowerManager的newWakeLock((int flags, String tag)來生成WakeLock執行個體。int Flags訓示要擷取哪種WakeLock,不同的Lock對cpu 、螢幕、鍵盤燈有不同影響。

擷取WakeLock執行個體後通過acquire()擷取相應的鎖,然後進行其他業務邏輯的操作,最後使用release()釋放(釋放是必須的)。

關于int flags(為PowerManager的關鍵字)

各種鎖的類型對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方法裡面釋放。