首頁 > 軟體

Android實現螢幕保持常亮功能

2022-01-18 10:01:08

本文範例為大家分享了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
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com