This article shares the specific code for Android to keep the screen bright for your reference. The specific content is as follows
1. Requirement background
When we don’t want the app to black screen when playing games or watching videos, we need to be in a constant state when using the app.
2. Implementation plan
1. Use
PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE); if (powerManager != null) { wakeLock = (PowerManager.FULL_WAKE_LOCK, "WakeLock"); (); //The screen is always on //(); // Release wakeLock, note that this method may have exceptions. For details, please refer to the source code. }
2. MediaPlayer has its own method to prevent the screen from being black
(true);
The source code is as follows:
/** * 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) { (TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder"); } mScreenOnWhilePlaying = screenOn; updateSurfaceScreenOn(); } } ...... private void updateSurfaceScreenOn() { if (mSurfaceHolder != null) { (mScreenOnWhilePlaying && mStayAwake); } }
3. Set it in the view
setKeepScreenOn(true/false), you can also set android:keepScreenOn="" in xml, and it will take effect as long as the View is visible.
4. Set up by adding flag
/** * Whether the screen is turned on or not */ private var enableKeepScreenOn = false /** * activity lifecycle listener */ private var mActivityLifecycleCallbacks = object : { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { //Set the screen to keep it light when the activity is created if (enableKeepScreenOn) { (.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) { } } /** * Set to keep the screen on */ fun setKeepScreenOn(enable: Boolean) { enableKeepScreenOn = enable }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.