Android提供的系统服务之--PowerManager(电源服务)
――转载请注明出处:coder-pig
本节引言:
本节主要讲授的Android为我们提供的系统服务中的:PowerManager电源管理的1个API,
用于管理CPU运行,键盘或屏幕亮起来;不过,除非是迫不得已吧,不然的话,否则应当尽可能避免
使用这个类,并且使用完以后1定要及时释放!本节其实不太深入的去讲授,由于这个设计到底层的
1些东西,以后需要用到再深入研究,到时再另外写1篇blog总结!所以本节介绍的主要是
1些基本的概念,PowerManager,wakelock锁的机制等等!
本节知识点图:
代码示例:
1个管理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⑵7411029-id⑷040727.html