Android实现屏幕保持常亮功能
本文实例为大家分享了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);
源码如下:
/** * 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); } }
3、在view中设置
setKeepScreenOn(true/false),同样可以在xml中设置android:keepScreenOn="",只要View可见即生效。
4、通过添加flag的方法设置
/** * 是否开启屏幕常亮 */ private var enableKeepScreenOn = false /** * activity 生命周期监听器 */ 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 }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)