Android保持屏幕常亮,PowerManager.WakeLock的使用
package com.hebaijun.wakelock; import android.app.Activity; import android.os.Bundle; import android.os.PowerManager; public class WakeLockActivity extends Activity { PowerManager.WakeLock wakeLock; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wakeLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "WakeLockActivity"); } @Override protected void onPause() { super.onPause(); if (wakeLock != null) { wakeLock.release(); } } @Override protected void onResume() { super.onResume(); wakeLock.acquire(); } }
需要在AndroidManifest.xml中添加权限<uses-permission android:name="android.permission.WAKE_LOCK"/>
- SCREEN_BRIGHT_WAKE_LOCK表示屏幕亮,键盘不亮。
- ON_AFTER_RELEASE表示执行 release方法后继续保持屏幕亮,直到默认超时后黑屏。
- 最好在 onResume方法中请求常亮,在 onPause方法中释放。
时间: 2024-10-21 02:06:05