本文实例为大家分享了Android实现屏幕保持常亮的具体代码,供大家参考,具体内容如下
一、需求背景
当我们在玩游戏或者看视频的时候不希望app黑屏,那么就需要在app使用的时候处于常量状态。
二、实现方案
1、使用PowerManager.WakeLock
PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "WakeLock");
wakeLock.acquire(); //开启屏幕常亮
//wakeLock.release(); //释放wakeLock,注意此方法可能出现异常.具体可看源码
}
2、MediaPlayer有自带的方法防止屏幕黑屏
mediaPlayer.setScreenOnWhilePlaying(true);
源码如下:
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);
}
}
3、在view中设置
setKeepScreenOn(true/false),同样可以在xml中设置android:keepScreenOn="",只要View可见即生效。
4、通过添加flag的方法设置
private var enableKeepScreenOn = false
private var mActivityLifecycleCallbacks = object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
//在activity创建的时候设置屏幕保持常亮
if (enableKeepScreenOn) {
activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityResumed(activity: Activity) {
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityDestroyed(activity: Activity) {
}
}
fun setKeepScreenOn(enable: Boolean) {
enableKeepScreenOn = enable
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。