android PowerManager(电源管理) wakelock(屏幕锁) .

合集下载

Android6.0 wakelock深入分析

Android6.0 wakelock深入分析

Android6.0 wakelock深入分析一、PowerManager的持锁接口我们先来看下PowerManager对应用提供的接口:[cpp] view plain copy 在CODE上查看代码片派生到我的代码片public WakeLock newWakeLock(int levelAndFlags, String tag) {validateWakeLockParameters(levelAndFlags, tag);//验证wakelock的flag是否有效return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());}validateWakeLockParameters函数如下:主要对flag没有下面这些flag做过滤[cpp] view plain copy 在CODE上查看代码片派生到我的代码片public static void validateWakeLockParameters(int levelAndFlags, String tag) { switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {case PARTIAL_WAKE_LOCK://cpu锁case SCREEN_DIM_WAKE_LOCK://屏幕微亮,键盘暗case SCREEN_BRIGHT_W AKE_LOCK://屏幕亮,键盘暗case FULL_WAKE_LOCK://全亮case PROXIMITY_SCREEN_OFF_WAKE_LOCK:case DOZE_WAKE_LOCK:case DRAW_WAKE_LOCK:break;default:throw new IllegalArgumentException("Must specify a valid wake lock level.");}if (tag == null) {throw new IllegalArgumentException("The tag must not be null.");}}我们再看WakeLock类,先看下面两个持锁,第二个timeout的持锁,先持锁,然后发送一个延迟消息再解锁。

Android中系统自带锁WalkLock与KeyguardLock用法实例详解

Android中系统自带锁WalkLock与KeyguardLock用法实例详解

Android中系统⾃带锁WalkLock与KeyguardLock⽤法实例详解本⽂实例讲述了Android中系统⾃带锁WalkLock与KeyguardLock⽤法。

分享给⼤家供⼤家参考,具体如下:WalkLock - 顾名思义唤醒锁点亮屏幕⽤的 KeyguardLock - 顾名思义键盘锁解锁键盘⽤的详细介绍:1: WalkLock 唤醒锁- WalkLock真的能点亮屏幕吗?答案是肯定的。

可是有时候为什么不点亮屏幕,这个就是参数设置的问题了。

复制代码代码如下:PowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "Gank");PowerManager.FULL_WAKE_LOCK 这个参数是⼿机点亮的程度,(什么Cpu,屏幕亮度,键盘灯)PowerManager.ACQUIRE_CAUSES_WAKEUP 关键是这个参数的理解。

WalkLock点亮屏幕并⾮真的去点亮了屏幕,你可以理解为,它通过Android组件(Activity)去点亮了屏幕。

假如⼀个通知想去点亮屏幕,问题来了,它能点亮吗?肯定不⾏。

不过拥有这个PowerManager.ACQUIRE_CAUSES_WAKEU参数,你就可以点亮屏幕了。

它使WalkLock不再依赖组件就可以点亮屏幕了。

- WalkLock如何获得屏幕的状态?PowerManager.isScreenOn()⽅法;这个⽅法返回true: 屏幕是唤醒的返回false:屏幕是休眠的- WalkLock唤醒和休眠的⽅法?WalkLock.aquire() 在屏幕休眠的状态下唤醒屏幕WalkLock.release() 在屏幕点亮的状态下,使屏幕休眠。

WalkLock.release()这个⽅法有个需要注意的地⽅:例如:WalkLockA对象先唤醒了屏幕再使屏幕休眠,ok没问题屏幕本⾝就是唤醒状态,WalkLockA对象没有唤醒过屏幕,WalkLockA对象如果尝试使屏幕休眠。

android休眠唤醒流程2

android休眠唤醒流程2

android休眠唤醒流程2android系统⼀段时间没有操作,屏幕(screen)将从⾼亮(bright)变为暗淡(dim),如果再过段时间还是没有操作,屏幕(screen)从暗淡(dim)变为关闭(off).这时,系统将进⼊休眠.⽽对于某些需要保持系统唤醒甚⾄屏幕唤醒的应⽤(⽐如视频播放器和⾳乐播放器)来说,就必须要有⼀个机制,使得系统不进⼊休眠状态,设置保持屏幕亮屏状态.wakelock即⽤来实现以上⽬的先上⽹上偷来的⼀副图,说⼀下android系统的整个电源管理流程图接下来对每⼀个模块具体分析:powermanager对应⽂件是android/frameworks/base/core/java/android/os/PowerManager.java在Android中应⽤程序并不是直接同PowerManagerService交互的,⽽是通过PowerManager间接地与PowerManagerService打交道。

此⽂件定义了⼀个powermanager类.主要实现了1,wakelock的申请与释放public WakeLock newWakeLock(int flags, String tag)2,系统延时进⼊休眠public void userActivity(long when, boolean noChangeLights)3,系统强制休眠public void goToSleep(long time)4,屏幕亮度设置public void setBacklightBrightness(int brightness)5,屏幕状态查询public boolean isScreenOn()6,系统重启public void reboot(String reason)细节wakelock的申请与释放{@samplecode*PowerManager pm = (PowerManager)mContext.getSystemService(* Context.POWER_SERVICE);*PowerManager.WakeLock wl = pm.newWakeLock(* PowerManager.SCREEN_DIM_WAKE_LOCK* | PowerManager.ON_AFTER_RELEASE,* TAG);*wl.acquire();* // ...*wl.release();⼀共有如下⼏个flag来进⾏不⼀样的唤醒⽅式.可以根据需要设置Flag Value CPU Screen KeyboardPARTIAL_WAKE_LOCK On* can-off OffSCREEN_DIM_WAKE_LOCK On Dim OffPROXIMITY_SCREEN_OFF_WAKE_LOCK on 距离传感器时关闭 offSCREEN_BRIGHT_WAKE_LOCK On Bright OffFULL_WAKE_LOCK On Bright BrightACQUIRE_CAUSES_WAKEUP 确保wakelock,主要⽤于视频播放器ON_AFTER_RELEASE = 0x20000000 release后倒计时,关闭屏幕...userActivity的作⽤:使系统从其他状态进⼊全部打开状态,⽐如从暗屏(dim)切换到亮屏,并重置倒计时计数器(待续)。

Android7.0PowerManagerService之亮灭屏(一)

Android7.0PowerManagerService之亮灭屏(一)

Android7.0PowerManagerService之亮灭屏(⼀)本篇从按下power按键后,按键事件从InputManagerService 传到PhoneWindowManager.java开始分析power 按键做屏幕亮灭过程的分析,关于power 按键的其他⾏为参考另⼀篇博⽂()(注:博客园显⽰的图⽚很模糊,上传的为⼤图,可以图⽚另存为查看)⾔归正传,本篇涉及的⼏个模块(⽂件)如下,先做个简单的介绍有个直观⼤概的了解,⽅便后⾯流程细节的理解。

Ø PowerManagerService.Java:(/frameworks/base/services/core/java/com/android/server/policy/PhoneWindowManager.java) PMS,是Android系统中的电源处理服务,主要负责电源相关的计算和决策,如是否应该灭屏或者让屏幕变暗,是否应该让系统休眠等等。

Ø DisplayPowerController.java:(/frameworks/base/services/core/java/com/android/server/display/DisplayPowerController.java) DPC,管理显⽰设备(这⾥指的显⽰设备是屏幕)状态,主要处理距离传感器(如打电话时候靠近则灭屏,离开时候屏幕亮起)以及亮灭屏动画(包括根据光感传感器计算屏幕⽬标亮度值)。

在DisplayManagerService.java(DMS)中实例化⼀个对象,以DMS为桥梁与PMS进⾏交互通过异步回调机制来通知PMS那些发⽣了改变。

同时也与WMS进⾏交互。

Ø DisplayPowerState.java:(/frameworks/base/services/core/java/com/android/server/display/DisplayPowerState.java) DPS,管理显⽰设备的状态仅在DPC中实例化⼀个对象,是DPC的⼀部分。

Android熄屏与亮屏控制

Android熄屏与亮屏控制

Android熄屏与亮屏控制目前做一个电子班牌的项目,需要做到熄屏与亮屏,网上找了很多,都是利用PowerManager,但是需要系统权限,这个比较麻烦,后面找到一个,测试发现可行的方案,就是利用设备管理器DevicePolicyManager执行熄屏,利用PowerManager进行亮屏,下面是步骤与代码。

1.注册:DeviceAdminReceiver<receiverandroid:name=".sreencontroldemo.Sc reenOffAdminReceiver"android:label="@string/app_name"android:permission="android.permission.BIND_DEVICE_AD MIN" ><meta-dataandroid:name="android.app.device_admin"android:resource="@xml/device_admin" /><intent-filter><actionandroid:name="android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter></receiver>ScreenOffAdminReceiver为继承DeviceAdminReceiver:public class ScreenOffAdminReceiver extends DeviceAdminReceiver {private void showT oast(Context context, String msg) {Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();}@Overridepublic void onEnabled(Context context, Intent intent) { showToast(context,"设备管理器使能");}@Overridepublic void onDisabled(Context context, Intent intent) { showToast(context,"设备管理器没有使能");}}device_admin为device_admin.xml,在res/xml文件夹下面:<?xml version="1.0" encoding="utf-8"?><device-admin xmlns:android="/apk/res/android"><uses-policies><limit-password /><reset-password /><force-lock /></uses-policies></device-admin>2.xml代码:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android" xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".sreencontroldemo.Ma inActivity"><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:onClick="checkScreen"android:text="检测屏幕状态" /><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:onClick="checkScreenOn"android:text="亮屏" /><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:onClick="checkScreenOff"android:text="熄屏" /><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:onClick="checkScreenOffAndDelayOn"android:text="熄屏后再亮屏" /><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:onClick="checkAndTurnOnDeviceManager"android:text="去启动设备管理器权限" /></LinearLayout>3.MainActivity代码:public class MainActivity extends AppCompatActivity {private String tag = "MainActivity";private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case 1:checkScreenOn(null);break;case 2:break;}}};private DevicePolicyManager policyManager;private ComponentName adminReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);adminReceiver = new ComponentName(MainActivity.this, ScreenOffAdminReceiver.class);mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);policyManager = (DevicePolicyManager) MainActivity.this.getSystemService(Context.DEVICE_POLICY_SER VICE);checkAndTurnOnDeviceManager(null);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);isOpen();}private void isOpen() {if (policyManager.isAdminActive(adminReceiver)) {//判断超级管理员是否激活showToast("设备已被激活");} else {showToast("设备没有被激活");}}private PowerManager mPowerManager;private PowerManager.WakeLock mWakeLock;/*** @param view 检测屏幕状态*/public void checkScreen(View view) {PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);boolean screenOn = pm.isScreenOn();if (!screenOn) {//如果灭屏//相关操作showToast("屏幕是息屏");} else {showToast("屏幕是亮屏");}}/*** @param view 亮屏*/public void checkScreenOn(View view) {mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT _WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");mWakeLock.acquire();mWakeLock.release();}/*** @param view 熄屏*/public void checkScreenOff(View view) {boolean admin = policyManager.isAdminActive(adminReceiver);if (admin) {policyManager.lockNow();} else {showToast("没有设备管理权限");}}/*** @param view 熄屏并延时亮屏*/public void checkScreenOffAndDelayOn(View view) {boolean admin = policyManager.isAdminActive(adminReceiver);if (admin) {policyManager.lockNow();handler.sendEmptyMessageDelayed(1, 3000);} else {showToast("没有设备管理权限");}}/*** @param view 检测并去激活设备管理器权限*/public void checkAndTurnOnDeviceManager(View view) {Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMI N, adminReceiver);intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANA TION, "开启后就可以使用锁屏功能了...");//显示位置见图二startActivityForResult(intent, 0);}private void showT oast(String Str) {Toast.makeText(this, Str, Toast.LENGTH_SHORT).show();}}4.发现的问题如果手机有屏保,熄屏后再亮屏会显示屏保。

Android中保持屏幕常亮的方法

Android中保持屏幕常亮的方法

Android中保持屏幕常亮的⽅法⼀、简要记录下,Android中保持屏幕常亮的⽅法:1、作⽤于View的:setKeepScreenOn(true/false),同样可以在xml中设置android:keepScreenOn="",只要View可见即⽣效。

2、通过添加flag的形式实现:添加:mActivity.getWindow().addFlags(youtParams.FLAG_KEEP_SCREEN_ON);清除:getWindow().clearFlags(youtParams.FLAG_KEEP_SCREEN_ON);3、使⽤PowerManager.WakeLock:PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);if (powerManager != null) {wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "WakeLock"); wakeLock.acquire(); //开启屏幕常亮 //wakeLock.release(); //释放wakeLock,注意此⽅法可能出现异常.具体可看源码} 在⾃测⼿机中并未出现异常,也就是说,并⾮⼀定不可以连续调⽤wakeLock.acquire()和wakeLock.release()。

4、第三种官⽅已经不推荐使⽤,建议使⽤上述1、2两种⽅法。

⼆、其他:1、在视频录制或播放中,MediaPlayer提供了相关⽅法实现屏幕常亮,具体如下: mMediaPlayer.setScreenOnWhilePlaying(true);源码如下:/*** Control whether we should use the attached SurfaceHolder to keep the* screen on while video playback is occurring. This is the preferred* method over {@link #setWakeMode} where possible, since it doesn't* require that the application have permission for low-level wake lock* access.** @param screenOn Supply true to keep the screen on, false to allow it* to turn off.*/public void setScreenOnWhilePlaying(boolean screenOn) {if (mScreenOnWhilePlaying != screenOn) {if (screenOn && mSurfaceHolder == null) {Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");}mScreenOnWhilePlaying = screenOn;updateSurfaceScreenOn(); //#}} ......private void updateSurfaceScreenOn() {if (mSurfaceHolder != null) { mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake); //#}}2、附上WakeLock的部分源码,它是PowerManager的内部类,可重点查看release(...):public final class WakeLock {......private boolean mRefCounted = true; //默认true......WakeLock(int flags, String tag, String packageName) {mFlags = flags;mTag = tag;mPackageName = packageName;mToken = new Binder(); //⽤于同步synchronizedmTraceName = "WakeLock (" + mTag + ")";}@Overrideprotected void finalize() throws Throwable {synchronized (mToken) {if (mHeld) {Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);try {mService.releaseWakeLock(mToken, 0);} catch (RemoteException e) {}}}}/*** Sets whether this WakeLock is reference counted.* <p>* Wake locks are reference counted by default. If a wake lock is* reference counted, then each call to {@link #acquire()} must be* balanced by an equal number of calls to {@link #release()}. If a wake* lock is not reference counted, then one call to {@link #release()} is* sufficient to undo the effect of all previous calls to {@link #acquire()}.* </p>** @param value True to make the wake lock reference counted, false to* make the wake lock non-reference counted.*/public void setReferenceCounted(boolean value) {synchronized (mToken) {mRefCounted = value;}}/*** Acquires the wake lock.* <p>* Ensures that the device is on at the level requested when* the wake lock was created.* </p>*/public void acquire() {synchronized (mToken) {acquireLocked();}}/*** Acquires the wake lock with a timeout.* <p>* Ensures that the device is on at the level requested when* the wake lock was created. The lock will be released after the given timeout* expires.* </p>** @param timeout The timeout after which to release the wake lock, in milliseconds.*/public void acquire(long timeout) {synchronized (mToken) {acquireLocked();mHandler.postDelayed(mReleaser, timeout);}}private void acquireLocked() {if (!mRefCounted || mCount++ == 0) {// Do this even if the wake lock is already thought to be held (mHeld == true)// because non-reference counted wake locks are not always properly released.// For example, the keyguard's wake lock might be forcibly released by the// power manager without the keyguard knowing. A subsequent call to acquire// should immediately acquire the wake lock once again despite never having// been explicitly released by the keyguard.mHandler.removeCallbacks(mReleaser);Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);try {mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource, mHistoryTag);} catch (RemoteException e) {}mHeld = true;}}/*** Releases the wake lock.* <p>* This method releases your claim to the CPU or screen being on.* The screen may turn off shortly after you release the wake lock, or it may* not if there are other wake locks still held.* </p>*/public void release() {release(0);}/*** Releases the wake lock with flags to modify the release behavior.* <p>* This method releases your claim to the CPU or screen being on.* The screen may turn off shortly after you release the wake lock, or it may* not if there are other wake locks still held.* </p>** @param flags Combination of flag values to modify the release behavior.* Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported. * Passing 0 is equivalent to calling {@link #release()}.*/public void release(int flags) {synchronized (mToken) {if (!mRefCounted || --mCount == 0) { //,满⾜任意条件即可执⾏mHandler.removeCallbacks(mReleaser);if (mHeld) { //满⾜条件,才能执⾏mService.releaseWakeLockTrace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);try {mService.releaseWakeLock(mToken, flags);} catch (RemoteException e) {}mHeld = false;}}if (mCount < 0) { //抛出异常throw new RuntimeException("WakeLock under-locked " + mTag);}}}......}View Code。

wakelock用法

wakelock用法

wakelock用法Wakelock是Android开发中非常重要的一个概念,它允许应用程序保持设备处于唤醒状态,以便执行任务或运行服务,而不会受到设备休眠的干扰。

Wakelock的原理是在应用程序需要保持设备唤醒状态时,获得设备CPU的锁,防止CPU进入睡眠模式,从而保证应用程序可以继续执行任务或运行服务。

但是,Wakelock在使用时也会导致设备耗电量增加,因此应该在必要的情况下谨慎使用。

使用Wakelock需要了解以下几个方面:1. 获取Wakelock:可以通过PowerManager的acquire方法获取一个Wakelock实例。

在获取Wakelock实例时,可以传递不同参数来控制设备的唤醒方式,例如PARTIAL_WAKE_LOCK表示设备只保持CPU唤醒,而屏幕和键盘灯会关闭;FULL_WAKE_LOCK表示设备保持CPU、屏幕和键盘灯均保持唤醒。

2. 释放Wakelock:在使用完Wakelock后,需要通过Wakelock的release方法来释放锁,以允许设备进入休眠状态。

如果不释放Wakelock,则可能会导致设备的电量快速消耗。

为了确保Wakelock被正确释放,建议将其放置在finally块中。

3. 使用场景:Wakelock适用于需要长时间执行任务或运行服务的场景,例如下载长时间需要的文件、播放音乐、持续运行后台服务等。

在使用Wakelock时,需要选择合适的锁类型和释放时机,以避免不必要的电量消耗和资源浪费。

4. Wakelock的注意事项:由于Wakelock会导致设备耗电量增加,因此在使用Wakelock时需谨慎,建议在必要的情况下使用。

此外,在获取Wakelock实例时应使用Context.getSystemService(Context.POWER_SERVICE)来获取PowerManager实例,避免内存泄漏问题。

android5.1 PowerManagerService和DisplayPowerControler、DisplayPowerState关系

android5.1 PowerManagerService和DisplayPowerControler、DisplayPowerState关系

android5.1 PowerManagerService和DisplayPowerControler、DisplayPowerState关系PowerManagerService在updateDisplayPowerStateLocked中与DisplayPowerControler交互,详细看代码:[java] view plain copyprivate boolean updateDisplayPowerStateLocked(int dirty) {final boolean oldDisplayReady = mDisplayReady;if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_W AKEFULNESS| DIRTY_ACTUAL_DISPLAY_POWER_STA TE_UPDA TED | DIRTY_BOOT_COMPLETED| DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST)) != 0) { mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();// Determine appropriate screen brightness and auto-brightness adjustments.int screenBrightness = mScreenBrightnessSettingDefault;float screenAutoBrightnessAdjustment = 0.0f;boolean autoBrightness = (mScreenBrightnessModeSetting ==Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {screenBrightness = mScreenBrightnessOverrideFromWindowManager;autoBrightness = false;} else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {screenBrightness = mTemporaryScreenBrightnessSettingOverride;} else if (isValidBrightness(mScreenBrightnessSetting)) {screenBrightness = mScreenBrightnessSetting;}if (autoBrightness) {screenBrightness = mScreenBrightnessSettingDefault;if (isValidAutoBrightnessAdjustment(mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {screenAutoBrightnessAdjustment =mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;} else if (isValidAutoBrightnessAdjustment(mScreenAutoBrightnessAdjustmentSetting)) {screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;}}screenBrightness = Math.max(Math.min(screenBrightness,mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);screenAutoBrightnessAdjustment = Math.max(Math.min(screenAutoBrightnessAdjustment, 1.0f), -1.0f);// Update display power request.mDisplayPowerRequest.screenBrightness = screenBrightness;mDisplayPowerRequest.screenAutoBrightnessAdjustment =screenAutoBrightnessAdjustment;eAutoBrightness = autoBrightness;eProximitySensor = shouldUseProximitySensorLocked();mDisplayPowerRequest.lowPowerMode = mLowPowerModeEnabled;mDisplayPowerRequest.boostScreenBrightness = mScreenBrightnessBoostInProgress;if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) { mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;mDisplayPowerRequest.dozeScreenBrightness =mDozeScreenBrightnessOverrideFromDreamManager;} else {mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;}mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,//调用DisplayPowerControler的requestPowerstate接口mRequestWaitForNegativeProximity);mRequestWaitForNegativeProximity = false;}return mDisplayReady && !oldDisplayReady;}接下来我们再看看mDisplayManagerInternal这个成员变量:在systemready中[java] view plain copymDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);。

Android_power_manager

Android_power_manager

Android 的电源管理也是很重要的一部分。

比如在待机的时候关掉不用的设备,timeout之后的屏幕和键盘背光的关闭,用户操作的时候该打开多少设备等等,这些都直接关系到产品的待机时间,以及用户体验。

framework层主要有这两个文件:frameworks\base\core\java\android\os\PowerManager.javaframeworks\base\services\java\com\android\server\PowerManagerService.java其中PowerManager.java是提供给应用层调用的,最终的核心还是在PowerManagerService.java。

这个类的作用就是提供PowerManager的功能,以及整个电源管理状态机的运行。

里面函数和类比较多,就从对外和对内分两块来说。

先说对外,PowerManagerService如何来进行电源管理,那就要有外部事件的时候去通知它,这个主要是在frameworks\base\services\java\com\android\server\WindowManagerService.java里面。

WindowManagerService会把用户的点击屏幕,按键等作为user activity事件来调用userActivity函数,PowerManagerService就会在userActivity里面判断事件类型作出反映,是点亮屏幕提供操作,还是完全不理会,或者只亮一下就关掉。

供WindowManagerService调用的方法还有gotoSleep 和其他一些获取电源状态的函数比如screenIsOn等等。

在说对内,作为对外接口的userActivity方法主要是通过setPowerState来完成功能。

把要设置的电源状态比如开关屏幕背光什么的作为参数调用setPowerState,setPowerState先判断下所要的状态能不能完成,比如要点亮屏幕的话但是现在屏幕被lock了那就不能亮了,否则就可以调用Power.setScreenState(true)来透过jni跑到driver里面去点亮屏幕了。

Android4.2之PowerManagerService设置亮度学习

Android4.2之PowerManagerService设置亮度学习

Android4.2中的PowerManagerService的设置亮度学习在PowerManagerService中,一个重要的Flag就是mDirty【private int mDirty;】,这个标志被完全彻底充分的使用了起来。

他一共支持设置十二位,分别是wake_lock锁状态,wakefulness清醒态,UserActivity用户态,actual display power state update显示器电源状态更新态,boot complete启动完成态,setting设置变化态,Powered充电态,stay on 持久态,battery state电池状态变化,proximity state距离传感器变化态,screen on blocker state became held or unheld保持屏幕亮或者改变和dock state changed(Unknow,类似于一种暂停态的状态)每次,当发生了点击事件或者申请了lock的时候,都会首先去更新这个mDirty,而不是立即去执行UpdatePowerState。

以UserActivity入口。

UserActivity函数同时也是作为PowerManager的API接口。

这里说下PowerManager和PowerManagerService之间的关系,他们通过Binder机制实现通信,具体表现就是PowerManager调用了PowerManagerService的AIDL接口,这个接口文件位于/frameworks/base/core/java/android/os/IPowerManager.aidl。

当用户调用UserActivity的时候实际就是调用PowerManagerService中的UserActivity,其它几个接口也都大抵如此,所以拿这一个说事儿就行。

userActivity()函数中,首先,取得当前时间,取得这个时间的作用不太大,主要是为了记录本次权限申请的log。

Android解除屏幕锁的方法

Android解除屏幕锁的方法

第一个方法:Android修改源代码控制永不锁屏锁定屏幕对于移动终端来说是非常有必要的,但是对于机顶盒产品就没有这个必要了。

所以本文介绍一下怎样让Android设备永不锁屏。

Android 系统的锁屏时间存放在Setting数据库中,字段为Settings.System.SCREEN_OFF_TIMEOUT。

查看SettingsProvider源码,查看如下文件的源码:frameworks/base/packages/SettingsProvider/src/com/Android/providers/settings/DatabaseHelper. java 查看loadSystemSettings()函数的代码如下:private voidloadSystemSettings(SQLiteDatabase db) { SQLiteStatement stmt =pileStatement("INSERT OR IGNORE INTO system(name,value)" + " VALUES(?,?);"); Resources r = mContext.getResources(); loadBooleanSetting(stmt,Settings.System.DIM_SCREEN, R.bool.def_dim_screen); loadSetting(stmt,Settings.System.STAY_ON_WHILE_PLUGGED_IN,"1".equals(SystemProperties.get("ro.kernel.qemu")) ? 1 : 0); loadIntegerSetting(stmt,Settings.System.SCREEN_OFF_TIMEOUT, R.integer.def_screen_off_timeout); // Set default cdma emergency tone loadSetting(stmt, Settings.System.EMERGENCY_TONE, 0); // Set default cdma call auto retry loadSetting(stmt, Settings.System.CALL_AUTO_RETRY, 0); // Set default cdma DTMF type loadSetting(stmt, Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, 0); // Set default hearing aid loadSetting(stmt, Settings.System.HEARING_AID, 0); // Set default tty mode loadSetting(stmt, Settings.System.TTY_MODE, 0); loadBooleanSetting(stmt, Settings.System.AIRPLANE_MODE_ON, R.bool.def_airplane_mode_on);loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_RADIOS,R.string.def_airplane_mode_radios); loadStringSetting(stmt,Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,R.string.airplane_mode_toggleable_radios); loadBooleanSetting(stmt,Settings.System.AUTO_TIME, R.bool.def_auto_time); // Sync time to NITZ loadIntegerSetting(stmt, Settings.System.SCREEN_BRIGHTNESS,R.integer.def_screen_brightness); loadBooleanSetting(stmt,Settings.System.SCREEN_BRIGHTNESS_MODE,R.bool.def_screen_brightness_automatic_mode); loadDefaultAnimationSettings(stmt); loadBooleanSetting(stmt, Settings.System.ACCELEROMETER_ROTATION,R.bool.def_accelerometer_rotation); loadDefaultHapticSettings(stmt); stmt.close(); } 从代码中我们可以看出,假如Settings.System.SCREEN_OFF_TIMEOUT没有初始化的话(系统首次启动,这个字段肯定是没有初始化的),将会利用资源中的R.integer.def_screen_off_timeout来初始化。

android系统电源管理----regulator的使用

android系统电源管理----regulator的使用

android系统电源管理----regulator的使⽤android系统电源管理----regulator的使⽤例:触摸屏它使⽤了⼀路regulator,他在机器suspend的时候要求关电(或者说低电),在机器开屏的时候才要求上电使⽤.那么:使⽤过程是这样的:1.我们先注册⼀个全局的regulatorstatic struct regulator *nabi2_dsi_reg = NULL;2.然后get regulatornabi2_dsi_reg = regulator_get(NULL, "avdd_dsi_csi");这个我们应该有印象,在平台设备注册的时候我们有注册它.如:static struct regulator_consumer_supply max77663_ldo7_supply[] ={REGULATOR_SUPPLY("avdd_dsi_csi",NULL),REGULATOR_SUPPLY("pwrdet_mipi",NULL),};Ok,之前我们注册了它,现在我们得到它3.给它上电就使能它regulator_enable(nabi2_dsi_reg);4.我们不再需要的时候就禁⽌它,以及放回它的使⽤权.regulator_disable(nabi2_dsi_reg);regulator_put(nabi2_dsi_reg);还有⼀些操作函数如://通过此接⼝获取输出电压int regulator_get_voltage(struct regulator *regulator)//调节电压的最⼩和最⼤输出。

如果接下去调⽤regulator_enable ,那么这个值马上就⽣效,如果调⽤regulator_disable等其他的,要等到下⼀次调⽤regulator_enable时才能⽣效。

int regulator_set_voltage(regulator,min_uV,max_uV);//强制关闭电源int regulator_force_disable(regulator);//关闭电源输出。

Android学习之wakelocks

Android学习之wakelocks

为了工作而工作是悲哀的!工作是实现自我价值的地方!程序员生涯的沉淀,感悟,牢骚[置顶] Android学习之wakelocks分类: android kernel framework powermanage linux 2012-02-22 17:31 2569人阅读 评论(0) 收藏举报androidstructlisttimer数据结构Updated: 2013/03/18, 刚有时间浏览了最新的Android builder submit 2013的相关slides,其中有关于最新的android 对kernel的upstream的状态的总结,大家可以看看/images/stories/slides/abs2013_stultz.pdfWakelocks已经进入了kernel main stream:)wakelock是android基于kernel的APM之上,构建的一个新的电源管理层, 使得用户可以通过获得wakelock来使得系统不会进入低功耗状态.这里我们不讨论android这种实现的优劣, 只关注一下它的实现. 对于它的好坏以及对kernel的电源管理的讨论在最后的相关资料中都有详细的讨论,有兴趣的童鞋可以去参考参考.首先来看看相关代码的位置相关代码在内核的/kernel/power/目录下fbearlysuspend.cearlysuspend.cconsoleearlysuspend.cwakelock.cuserwakelock.c及相应的头文件: include/linux/wakelock.h接着主要关注wakelock的实现:1.主要的数据结构wakelock的两种状态, 前者表示还不能suspend,后者表示可以suspeenum {WAKE_LOCK_SUSPEND, /* Prevent suspend */WAKE_LOCK_IDLE, /* Prevent low power idle */WAKE_LOCK_TYPE_COUNT};struct wake_lock, 其中可以看出wakelock是由list管理起来, 并且有相应的过期时间及一些stat信息. 而且会有两个list分别对应上述两种类型的wakelockstruct wake_lock {#ifdef CONFIG_HAS_WAKELOCKstruct list_head link;int flags;const char *name;unsigned long expires;#ifdef CONFIG_WAKELOCK_STATstruct {int count;int expire_count;int wakeup_count;ktime_t total_time;ktime_t prevent_suspend_time;ktime_t max_time;ktime_t last_time;} stat;#endif#endif};static struct list_head active_wake_locks[WAKE_LOCK_TYPE_COUNT];static LIST_HEAD(inactive_locks);struct workqueue_struct *suspend_work_queue; //用内核提供的workqueue来缓冲需要suspend的动作 //这里从后面的初始化可以看出使用的create_singlet //意味着整个系统只有一个对应的workqueue,而不是pe struct wake_lock main_wake_lock; // 四个不同用途的wake_lock, 后面会介绍用处static struct wake_lock unknown_wakeup;static struct wake_lock suspend_backoff_lock;static struct wake_lock deleted_wake_locks;suspend_state_t requested_suspend_state = PM_SUSPEND_MEM //这里表示wakelock使用的suspend这里解释一下内核电源管理中定义的几种PM suspend的状态PM_SUSPEND_ON, 通常的运行状态PM_SUSPEND_STANDBY, 待机状态, 外围设备不供电,而CPU进入低功耗状态PM_SUSPEND_MEM, 与STANDBY类似, 除此之外,CPU也会进入power off状态, 并把CPU的state转存到对应的SDRAM中,以便之后的suspend能够从中恢复CPU及kernel的运行状态PM_SUSPEND_MAX, 表示所有设备都不工作了, 并把处于suspend到disk的状态这里需要注意的是, 在SoC的环境下, 不同的厂商会有各自实现的PM, 所以有些驱动会需要在这两者之间进行必要的mapping.参见:OMAP3的suspend支持为了使得user能够通过wakelock提供的接口获取释放wakelock, 就像其它Android新增的内核模块一样, 这个wakelock设备被以platoform device&driver的方式实现.static struct dev_pm_ops power_driver_pm_ops = {.suspend_noirq = power_suspend_late, //参见devices.txt的解释};static struct platform_driver power_driver = { = "power",.driver.pm = &power_driver_pm_ops,};static struct platform_device power_device = {.name = "power",};2.主要的函数wakelocks_init 主要分为4个部分,如下static int __init wakelocks_init(void){int ret;int i;// 1.初始化上文提到的几个数据结构, 关键是4种wakelock的初始化:// deleted_wake_locks// main// unknown_wakeups// suspend_backofffor (i = 0; i < ARRAY_SIZE(active_wake_locks); i++)INIT_LIST_HEAD(&active_wake_locks[i]);#ifdef CONFIG_WAKELOCK_STATwake_lock_init(&deleted_wake_locks, WAKE_LOCK_SUSPEND,"deleted_wake_locks");#endifwake_lock_init(&main_wake_lock, WAKE_LOCK_SUSPEND, "main");wake_lock(&main_wake_lock);wake_lock_init(&unknown_wakeup, WAKE_LOCK_SUSPEND, "unknown_wakeups");wake_lock_init(&suspend_backoff_lock, WAKE_LOCK_SUSPEND,"suspend_backoff");// 2. 注册wakelocks的对外接口设备powerret = platform_device_register(&power_device);if (ret) {pr_err("wakelocks_init: platform_device_register failed\n");goto err_platform_device_register;}ret = platform_driver_register(&power_driver);if (ret) {pr_err("wakelocks_init: platform_driver_register failed\n");goto err_platform_driver_register;}// 3. 创建唯一的workqueue内核线程suspendsuspend_work_queue = create_singlethread_workqueue("suspend");if (suspend_work_queue == NULL) {ret = -ENOMEM;goto err_suspend_work_queue;}// 4. 在procfs中创建wakelocks数据节点, 即/proc/wakelocks, 所有的wakelocks stat信息都通过它#ifdef CONFIG_WAKELOCK_STATproc_create("wakelocks", S_IRUGO, NULL, &wakelock_stats_fops);#endifreturn 0;...return ret;}void wake_lock_init(struct wake_lock *lock, int type, const char *name)void wake_lock_init(struct wake_lock *lock, int type, const char *name)初始化各个wakelock,并加入到对应的inactive_locks list关键的wake_lock_internal函数, 用来响应所有对wake_lock/wake_unlock的调用static void wake_lock_internal(struct wake_lock *lock, long timeout, int has_timeout){int type;unsigned long irqflags;long expire_in;// 获得每个wakelock的spin lockspin_lock_irqsave(&list_lock, irqflags);// 获得当前wakelock的类型type = lock->flags & WAKE_LOCK_TYPE_MASK;BUG_ON(type >= WAKE_LOCK_TYPE_COUNT);BUG_ON(!(lock->flags & WAKE_LOCK_INITIALIZED));// 获取一些当前wakelock的信息#ifdef CONFIG_WAKELOCK_STATif (type == WAKE_LOCK_SUSPEND && wait_for_wakeup) {if (debug_mask & DEBUG_WAKEUP)pr_info("wakeup wake lock: %s\n", lock->name);wait_for_wakeup = 0;lock->stat.wakeup_count++;}if ((lock->flags & WAKE_LOCK_AUTO_EXPIRE) &&(long)(lock->expires - jiffies) <= 0) {wake_unlock_stat_locked(lock, 0);lock->st_time = ktime_get();}#endifif (!(lock->flags & WAKE_LOCK_ACTIVE)) {lock->flags |= WAKE_LOCK_ACTIVE;#ifdef CONFIG_WAKELOCK_STATlock->st_time = ktime_get();#endif}list_del(&lock->link);// 根据是否是需要自动过期的锁来设定相应的过期时间// 这里需要注意的是// 如果是自动过期锁,则是一个queue类似的操作, 先进先出, 导致过期时先处理自动过期锁,再处理非自动过期 // 如果是非自动过期,则是一个stack类似的操作, 后进先出if (has_timeout) {if (debug_mask & DEBUG_WAKE_LOCK)pr_info("wake_lock: %s, type %d, timeout %ld.%03lu\n",lock->name, type, timeout / HZ,(timeout % HZ) * MSEC_PER_SEC / HZ);lock->expires = jiffies + timeout;lock->flags |= WAKE_LOCK_AUTO_EXPIRE;list_add_tail(&lock->link, &active_wake_locks[type]);} else {if (debug_mask & DEBUG_WAKE_LOCK)pr_info("wake_lock: %s, type %d\n", lock->name, type);lock->expires = LONG_MAX;lock->flags &= ~WAKE_LOCK_AUTO_EXPIRE;list_add(&lock->link, &active_wake_locks[type]);}if (type == WAKE_LOCK_SUSPEND) {current_event_num++;#ifdef CONFIG_WAKELOCK_STATif (lock == &main_wake_lock)update_sleep_wait_stats_locked(1);else if (!wake_lock_active(&main_wake_lock))update_sleep_wait_stats_locked(0);#endif// 获得当前的锁的还有多久过期if (has_timeout)expire_in = has_wake_lock_locked(type);elseexpire_in = -1;if (expire_in > 0) {if (debug_mask & DEBUG_EXPIRE)pr_info("wake_lock: %s, start expire timer, ""%ld\n", lock->name, expire_in);// 修改过期时间mod_timer(&expire_timer, jiffies + expire_in);} else {if (del_timer(&expire_timer))if (debug_mask & DEBUG_EXPIRE)pr_info("wake_lock: %s, stop expire timer\n",lock->name);// 如果当前过期了,则调用注册的work_queue函数suspend来进行相应动作 if (expire_in == 0)queue_work(suspend_work_queue, &suspend_work);}}spin_unlock_irqrestore(&list_lock, irqflags);}3.关键的suspend函数static void suspend(struct work_struct *work){int ret;int entry_event_num;struct timespec ts_entry, ts_exit;// 简单check, 如果到这里却发现没有处在suspend的wakelock,肯定有问题,直接退出.if (has_wake_lock(WAKE_LOCK_SUSPEND)) {if (debug_mask & DEBUG_SUSPEND)pr_info("suspend: abort suspend\n");return;}entry_event_num = current_event_num;// 系统进入suspend之前,需要进行必要的sync,保证一些重要数据不会丢失sys_sync();if (debug_mask & DEBUG_SUSPEND)pr_info("suspend: enter suspend\n");getnstimeofday(&ts_entry);// 调用kernel中的标准pm接口,发出suspend请求ret = pm_suspend(requested_suspend_state);getnstimeofday(&ts_exit);if (debug_mask & DEBUG_EXIT_SUSPEND) {struct rtc_time tm;rtc_time_to_tm(ts__sec, &tm);pr_info("suspend: exit suspend, ret = %d ""(%d-%02d-%02d %02d:%02d:%02d.%09lu UTC)\n", ret,tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,tm.tm_hour, tm.tm_min, tm.tm_sec, ts__nsec);}// 因为调用pm_suspend会有延迟,这里做一些微调if (ts__sec - ts__sec <= 1) {++suspend_short_count;if (suspend_short_count == SUSPEND_BACKOFF_THRESHOLD) {// 如果这时有多个wake lock suspend时间发生了,则做一定的延后suspend_backoff();suspend_short_count = 0;}} else {suspend_short_count = 0;}if (current_event_num == entry_event_num) {if (debug_mask & DEBUG_SUSPEND)pr_info("suspend: pm_suspend returned with no event\n");wake_lock_timeout(&unknown_wakeup, HZ / 2);}}其余的函数都是一些工具函数,相当简单,这里就偷懒不说了:)4.与驱动层的接口hardware/libhardware_legacy/power/power.c定义了3种可用的用户接口,与framework提供的功能对应enum {ACQUIRE_PARTIAL_WAKE_LOCK = 0,RELEASE_WAKE_LOCK,REQUEST_STATE,OUR_FD_COUNT};定义了3个sysfs的接口,用户通过操作对应的fd,来使用wakelock.const char * const NEW_PATHS[] = {"/sys/power/wake_lock","/sys/power/wake_unlock","/sys/power/state"};与之上面对应的几个函数, 都是通过操作对应的sysfs接口,来控制pm的行为. 其中参数id,就是你能够在/proc/wakelocks中看到的那些名字int acquire_wake_lock(int lock, const char* id)int release_wake_lock(const char* id)int set_screen_state(int on)5.framework层的接口frameworks/base/core/jni/android_os_Power.cppservices/java/com/android/server/PowerManagerService.javacmds/svc/src/com/android/commands/svc/PowerCommand.javacmds/svc/src/com/android/commands/svc/PowerCommand.java通过这些文件中的接口管理系统的power状态, 调用驱动层的接口, 控制内核适当的改变cpu/screen的供电状态.6.java层的接口参见/reference/android/os/PowerManager.html, 里面介绍的很清楚了,关于它的使用也有很多教程及建议,我就不在这里敷述了.其它,kernel-pm也提供了一个类似android wakelock的解决方案,值得一看(但是到目前为止,还没有merge到mainstream当中):/group/linux.kernel/browse_frm/thread/b6fed7e38365c259/c92d8b4a41f87902?hl=en &tvc=1&q=linux.kernel+suspend+block+api+(version+6)#相关资料:What comes after suspend blockers , 详细介绍了什么是suspend和idle, 内核如何处理它们, 以及android中的wakelock与内核中标准的suspend的区别标准内核中的suspend/idle实现是基于QOS的反馈来完成的其中提到了一个suspend block api,可以使得基于标准内核的驱动程序使用它来达到android实现的wakelock逻辑.不过,不知道有没有人这样用过pm_qos API用来提供内核所需要的关于power manager相关的QOS信息The cpuidle subsystem,/images/e/e6/Elce11_wysocki.pdf/images/0/09/Elce11_pieralisi.pdf--arm电源管理, 尤其针对CPU PW management/jserv/power-management-from-linux-kernel-to-android --Power Management from Linux Kernel to Android/images/pdf/suspend_blockers.pdf -- 关于android的wakelock的一个详细说明。

Android让屏幕保持常亮,不熄屏的三种方法

Android让屏幕保持常亮,不熄屏的三种方法

Android让屏幕保持常亮,不熄屏的三种⽅法⽅法⼀:持有WakeLock⾸先获取WakeLock相关权限:<uses-permission android:name="android.permission.WAKE_LOCK" />然后通过PowerManager获取WakeLock后,在onResume以及onPause执⾏相应操作:@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);if (powerManager != null) {mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "WakeLock");}}@Overrideprotected void onResume() {super.onResume();if (mWakeLock != null) {mWakeLock.acquire();}}@Overrideprotected void onPause() {super.onPause();if (mWakeLock != null) {mWakeLock.release();}}WakeLock获取时相关的flag如下所⽰:PARTIAL_WAKE_LOCK :保持CPU 运转,屏幕和键盘灯有可能是关闭的。

SCREEN_DIM_WAKE_LOCK :保持CPU 运转,允许保持屏幕显⽰但有可能是灰的,允许关闭键盘灯SCREEN_BRIGHT_WAKE_LOCK :保持CPU 运转,允许保持屏幕⾼亮显⽰,允许关闭键盘灯FULL_WAKE_LOCK :保持CPU 运转,保持屏幕⾼亮显⽰,键盘灯也保持亮度PS:现在官⽅已经不推荐使⽤这种⽅式保持亮屏了,推荐改为以下两种⽅式⽅式⼆:在Window设置flaggetWindow().addFlags(youtParams.FLAG_KEEP_SCREEN_ON);这种⽅式不需要申请权限,也是官⽅推荐的做法⽅式三:在界⾯布局xml中顶层添加属性可以再界⾯xml⽂件中的顶层布局添加属性即可:android:keepScreenOn="true"。

Android保持屏幕常亮2种实现方法

Android保持屏幕常亮2种实现方法
这篇文章主要介绍了详解关于androidq获取不到imsi解决方案文中通过示例代码介绍的非常详细对大家的学习或者工作具有一定的参考学习价值需要的朋友们下面随着小编来一起学习学习吧
Android保持屏幕常亮 2种实现方法
方法一:
复制代码 代码如下:
<uses-permission android:name="android.permission.WAKE_LOCK" />

//请求常亮,onResume() wakeLock.acquire();
//取消屏幕常亮,onPause() wakeLock.release();
方法二: 直接在onCreate()里,不用权限 复制代码 代码如下:
getWindow().addFlags(youtParams.FLAG_KEEP_SCREEN_ON);
复制代码 代码如下:
private PowerManager powerManager = null; private WakeLock wakeLock = null;
powerManager = (PowerManager) this.getSystemService(Service.POWER_SERVICE); wakeLock = this.powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Lock"); //是否需计算锁的数量 wakeLock.setReferenceCounted(false);

Android编程调节屏幕亮度(背景灯)及保持背景灯常亮的方法

Android编程调节屏幕亮度(背景灯)及保持背景灯常亮的方法

Android编程调节屏幕亮度(背景灯)及保持背景灯常亮的⽅法本⽂实例讲述了Android编程调节屏幕亮度(背景灯)及保持背景灯常亮的⽅法。

分享给⼤家供⼤家参考,具体如下:Android写的应⽤程序其实可以调节屏幕亮度的,查了⼀下资料发现youtParams这个类就包含了调节亮度的参数:youtParams lp = getWindow().getAttributes();lp.screenBrightness = 0.1f;其中参数screenBrightness就是设置屏幕亮度的0.0f屏幕最暗,1.0f屏幕最亮在此基础上我⼜加了⼀个SeekBar来调节屏幕亮度,代码参考如下:此外在回调函数中必须有如下这句话 getWindow().setAttributes(lp); 否则不起作⽤。

我在开始的时候在onCreate()函数中直接设的值,没有这个函数,就能直接调节,但是在回调函数中不加上就不起作⽤public class BLightActivity extends Activity {/** Called when the activity is first created. */int Max_Brightness = 100;SeekBar bSeekBar = null;float fBrightness = 0.0f;youtParams lp = null;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main);bSeekBar = (SeekBar) findViewById(R.id.bLightBar);bSeekBar.setOnSeekBarChangeListener(seekListener);bSeekBar.setMax(Max_Brightness);lp = getWindow().getAttributes();// lp.screenBrightness = 0.1f;}OnSeekBarChangeListener seekListener = new OnSeekBarChangeListener() {public void onStopTrackingTouch(SeekBar seekBar) {// TODO Auto-generated method stub}public void onStartTrackingTouch(SeekBar seekBar) {// TODO Auto-generated method stub}public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {// TODO Auto-generated method stubfBrightness = (float)progress / (float)Max_Brightness;lp.screenBrightness = fBrightness;// 这句得加上,否则屏幕亮度不启作⽤getWindow().setAttributes(lp);System.out.println("FY_" + fBrightness);}};}下⾯是介绍保持背景灯常量的⽅法:⾸先是要获得权限 :复制代码代码如下:<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>下⾯是控制代码实例public class test extends Activity{PowerManager powerManager = null;WakeLock wakeLock = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);this.setContentView(yout.main);this.powerManager = (PowerManager)this.getSystemService(Context.POWER_SERVICE);this.wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock"); this.wakeLock.acquire();}@Overrideprotected void onResume() {super.onResume();// 重新获取this.wakeLock.acquire();}@Overrideprotected void onPause() {super.onPause();// 在Activity销毁的时候释放wakeLockthis.wakeLock.release();}}更多关于Android开发相关内容感兴趣的读者可查看本站专题:《》希望本⽂所述对⼤家Android程序设计有所帮助。

Android休眠流程总结

Android休眠流程总结

Android休眠流程总结1. framework层1.1 java层休眠流程中上层有很多种,⽐如按power key进⼊休眠流程,还是就是settings下⾯的⾃动息屏流程。

1.1.1 power key休眠流程当⽤户按下power key的时候,PhoneWindowManager类下的interceptBeforeQueueing, 在handle special key流程中,会命中KeyEvent.KEYCODE_POWER.其业务逻辑⾥⾯就会调⽤到inteceptPowerKeyDown和interceptPowerKeyUp, ⽽休眠流程的起始条件,灭屏流程就是从这个interceptPowerKeyUp开始的。

之后会就interceptPowerKeyUp展开,但我们先来看下从key event发出后,怎么⾛到interceptBeforeQueueing的,这⾥主要看下framework层的获得key event事件后响应流程,⾄于key event事件怎么分发的和怎么获得的需要InuptDispatcher(inputFlinger)部分来分析,之后有时间再补充。

com_android_server_input_InputManagerService.cpp在收到InputDispatcher分发的出来PowerKey 事件之后,就会⾛到NativeInputManager::dispatchUnhandledKey⽅法,这⾥⽅法⾥通过回调的机制回调到InputManagerService.java下⾯的native⽅法dispatchUnhandleKey,注意这个⽅法是回调⽅法。

然后在调到InputManagerCallback下⾯的dispatchUnhandleKey,然后再调到PhoneWindowManager下⾯的dispatchUnhandleKey⽅法,然后调到interceptFallback⽅法,最终从这⾥⾯调到interceptBeforeQueueing这个⽅法。

Android功耗优化(7)---如何分析wakelock(wakeupsource)持锁问题

Android功耗优化(7)---如何分析wakelock(wakeupsource)持锁问题

Android功耗优化(7)---如何分析wakelock(wakeupsource)持锁问题如何分析wakelock(wakeup source)持锁问题锁⼀般分为:APP透过PowerManager拿锁,以及kernel wakelock.分析上层持锁的问题:⽬前PowerManagerService的log 默认不会打开,可以通过修改:frameworks/base/services/core/java/com/android/server/power/PowerManagerService.javaprivate static final boolean DEBUG = true;private static final boolean DEBUG_SPEW = DEBUG && false;修改为:private static final boolean DEBUG = true;private static final boolean DEBUG_SPEW = true;打开上层的log通过syslog:搜索关键字:total_time=来确定持锁的时间.PowerManagerService: releaseWakeLockInternal: lock=31602562 [*job*/DownloadManager:com.android.providers.downloads], flags=0x0, total_time=600051ms或者通过正则表达式:total_time=[\d]{4,}ms 过滤出持锁时间⽐较长的锁.PowerManagerService: releaseWakeLockInternal: lock=31602562 [*job*/DownloadManager:com.android.providers.downloads], flags=0x0, total_time=600051ms PowerManagerService: releaseWakeLockInternal: lock=56317918 [*job*/DownloadManager:com.android.providers.downloads], flags=0x0, total_time=283062ms PowerManagerService: releaseWakeLockInternal: lock=216012597 [AudioMix], flags=0x0, total_time=120003msPowerManagerService: releaseWakeLockInternal: lock=41036921 [AudioMix], flags=0x0, total_time=167984msPowerManagerService: releaseWakeLockInternal: lock=70859243 [GsmInboundSmsHandler], flags=0x0, total_time=3206msPowerManagerService: releaseWakeLockInternal: lock=242046348 [AudioMix], flags=0x0, total_time=122205mskernel的锁默认不会打印出来,⼀般是待机结束后通过节点来获取:adb shell cat /sys/kernel/debug/wakeup_sources > wakeup_sources.logactive_count:对应wakeup source被激活的次数.event_count:被信号唤醒的次数wakeup_count:中⽌suspend的次数.expire_count:对应wakeup source超时的次数.active_since:上⼀次还活跃的时间点.时间单位跟kernel log前缀时间是⼀样(kernel单调递增时间).total_time:对应wakeup source活跃的总时长.max_time:对应的wakeup source持续活跃最长的⼀次时间.last_change:上⼀次wakeup source变化的时间(从持锁到释放or释放到持锁),时间单位跟kernel log前缀时间是⼀样(kernel单调递增时间).prevent_suspend_time:对应wakeup source阻⽌进⼊autosleep的总累加时间.⼀般情况下:如果是复现机,前⾯没有捉log,也没有dump log,只有⼀份wakeup_sources.log可以看下prevent_suspend_time,⼀般时间越⼤越可能是阻⽌系统进⼊suspend的wakeup sources.如果测试前后,都有捉 wakeup_sources.log 请对两份wakeup_sources.log的total time的差值.差值时间跟灭屏的时间对得上,⼀般就是这个锁引起的问题.把捉出来的wakeup_sources.log复制到excel表格中,⽐较好对齐,⼀个是⽐较好计算.其中dispsys_wakelock total_time的时间有697614mS 也就是总共有697s.或者在待机测试结束后通过命令:adb bugreport > bugreport.txt搜索关键:底层的锁:All kernel wake locks:Kernel Wake lock ttyC0 : 1h 33m 15s 668ms (3856 times) realtimeKernel Wake lock radio-interface: 1h 20m 56s 210ms (3995 times) realtimeKernel Wake lock ccci3_at : 1h 9m 43s 491ms (2932 times) realtimeKernel Wake lock ccci_fs : 1h 0m 52s 818ms (3432 times) realtimeKernel Wake lock ccci3_at2 : 41m 16s 938ms (2465 times) realtime上层的锁:All partial wake locks:Wake lock 1001 RILJ: 5m 29s 768ms (13118 times) realtimeWake lock 1000 *alarm*: 4m 7s 823ms (2330 times) realtimeWake lock 1000 ConnectivityService: 59s 513ms (1 times) realtime Wake lock u0a111 *alarm*: 50s 334ms (751 times) realtimeWake lock u0a111 WakerLock:999603354: 28s 655ms (125 times) realtime Wake lock 1000 NetworkStats: 11s 434ms (569 times) realtime。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

android PowerManager(电源管理)wakelock(屏幕锁)
今天在看一个项目的源代码时,发现了这个电源管理和屏幕锁:PowerManager、wakelock。

其中在onStart()方法中获取wakelock,并且在onstop()中将这个lock释放掉。

protected v oid onStart() {
....
pm = (PowerManager) getSy stemServ ice(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, "MediaCenterApplication");
wl.acquire();
wl.setRef erenceCounted(f alse);
....
}
protected v oid onStop() {
....
wl.release();
....
}
PowerManager和WakeLock的操作步骤
1. PowerManager pm = (PowerManager) getSy stemServ ice(Context.POWER_SERVICE);通
过Context.getSystemService().方法获取PowerManager实例。

2. 然后通过PowerManager的newWakeLock
((int flags, String
tag)来生成WakeLock实例。

int Flags指示要获取哪种WakeLock,不同的Lock对cpu 、屏幕、键盘灯有不同影响。

3. 获取WakeLock实例后通过acquire()获取相应的锁,然后进行其他业务逻辑的操作,最后使用release()释放(释放是必须的)。

关于int flags
各种锁的类型对CPU 、屏幕、键盘的影响:
PA RTI A L_W A KE_LOCK:保持CPU 运转,屏幕和键盘灯有可能是关闭的。

SCREEN_DIM_W A KE_LOCK:保持CPU 运转,允许保持屏幕显示但有可能是灰的,允许关闭键盘灯
SCREEN_BRIGHT_W A KE_LOCK:保持CPU 运转,允许保持屏幕高亮显示,允许关闭键盘灯
FULL_WA KE_LOCK:保持CPU 运转,保持屏幕高亮显示,键盘灯也保持亮度
A C QUIRE_C A USES_W AKEUP:Normal wake locks don't actually turn on the illumination. Instead, they cause the illumination to remain on once it turns on (e.g. f rom user activ ity). This f lag will f orce the screen and/or key board to turn on immediately, when the WakeLock is acquired. A ty pical use would be f or notifications which are important f or the user to see immediately.
ON_AFTER_RE LE ASE:f this flag i s set, the user activity timer w ill be reset w hen the WakeLock is released, causing the illumination to remain on a bit longer. This can be used to reduce flicker i f you are cycling between wake lock conditions.
权限获取
要进行电源的操作需要在AndroidManif est.xml中声明该应用有设置电源管理的权限。

<uses-permission android:name="android.permission.WAKE_LOCK"/> 你可能还需要 <uses-permission
android:name="android.permission.DEVICE_POWER"/>。

相关文档
最新文档