mikebai.com

  • Home
  • dev
  • DotNET
  • M365
  • 搞笑
  • 杂七杂八
  • FocusDict
個人BLOG
it developer
  1. Main page
  2. dev
  3. Main content

android的PowerManager和PowerManager.WakeLock

2012-02-23 99hotness 0likes 0comments

保持android 屏幕常亮的方法


前言


  学习android一段时间了,为了进一步了解android的应用是如何设计开发的,决定详细研究几个开源的android应用。从一些开源应用中吸收点东西,一边进行量的积累,一边探索android的学习研究方向。这里我首先选择了jwood的 Standup Timer 项目。本文将把研究的内容笔记整理,建立一个索引列表。

PowerManager.WakeLock


  PowerManager.WakerLock是我分析Standup Timer源代码时发现的一个小知识点,Standup Timer 用WakeLock保证程序运行时保持手机屏幕的恒亮(程序虽小但也做得相当的细心,考虑的很周到)。PowerManager 和PowerManager.WakerLock7用于对Android设备的电源进行管理。

  PowerManager:This class gives you control of the power state of the device.

  PowerManager.WakeLock: lets you say that you need to have the device on.

  Android中通过各种Lock锁对电源进行控制,需要注意的是加锁和解锁必须成对出现。先上一段Standup Timer里的代码然后进行说明。



private void acquireWakeLock() {
if (wakeLock == null) {
Logger.d(
"Acquiring wake lock");
PowerManager pm
= (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock
= pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this.getClass().getCanonicalName());
wakeLock.acquire();
}

}

private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock
= null;
}

}
acquireWakeLock()方法中获取了 SCREEN_DIM_WAKE_LOCK锁,该锁使 CPU 保持运转,屏幕保持亮度(可以变灰)。这个函数在Activity的 onResume中被调用。releaseWakeLock()方法则是释放该锁。它在Activity的 onPause中被调用。利用Activiy的生命周期,巧妙的让 acquire()和release()成对出现。


@Override
protected void onResume()
{
super.onResume();
//获取锁,保持屏幕亮度
acquireWakeLock();
startTimer();
}

Tag: Nothing
Last updated:2012-02-23

mikebai

This person is a lazy dog and has left nothing

Like
< Last article
Next article >

COPYRIGHT © 2025 mikebai.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang