Android提供的系统服务之--PowerManager(电源服务)
——转载请注明出处:coder-pig
本节引言:
本节主要讲解的Android为我们提供的系统服务中的:PowerManager电源管理的一个API,
用于管理CPU运行,键盘或者屏幕亮起来;不过,除非是迫不得已吧,不然的话,否则应该尽量避免
使用这个类,并且使用完以后一定要及时释放!本节并不太深入的去讲解,因为这个设计到底层的
一些东西,以后需要用到再深入研究,到时再另外写一篇blog总结!所以本节介绍的主要是
一些基本的概念,PowerManager,wakelock锁的机制等等!
本节知识点图:
代码示例:
一个管理WakeLock以及Android设备电源管理的工具类:
import android.content.Context; import android.content.SharedPreferences; import android.os.PowerManager; import android.preference.PreferenceManager; public class ManageWakeLock { private static PowerManager.WakeLock mWakeLock = null; private static PowerManager.WakeLock mPartialWakeLock = null; private static final boolean PREFS_SCREENON_DEFAULT = true; private static final boolean PREFS_DIMSCREEN_DEFAULT = false; private static final String PREFS_TIMEOUT_DEFAULT = "30"; public static synchronized void acquireFull(Context mContext) { if (mWakeLock != null) { return; } PowerManager mPm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); int flags; flags = PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP; mWakeLock = mPm.newWakeLock(flags, “ManagerWakeLock”); mWakeLock.setReferenceCounted(false); mWakeLock.acquire(); } public static synchronized void acquirePartical(Context mContext) { //Check if partial lock already exists if (mPartialWakeLock != null) { return; } PowerManager mPm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); mPartialWakeLock = mPm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, “ManagerWakeLock”); mPartialWakeLock.setReferenceCounted(false); mPartialWakeLock.acquire(); } } public static synchronized void releaseFull() { if (mWakeLock != null) { mWakeLock.release(); mWakeLock = null; } } public static synchronized void releasePartial() { if (mPartialWakeLock != null) { mPartialWakeLock.release(); mPartialWakeLock = null; } } public static synchronized void releaseAll() { releaseFull(); releasePartial(); } }
参考资料:
http://www.open-open.com/lib/view/open1343207436974.html
http://blog.csdn.net/xieqibao/article/details/6562256
http://blog.chinaunix.net/uid-27411029-id-4040727.html
时间: 2024-10-21 03:58:08