这篇文章主要为大家详细介绍了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
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:Android实现屏幕保持常亮功能
基础教程推荐
猜你喜欢
- Android实现短信验证码输入框 2023-04-29
- IOS获取系统相册中照片的示例代码 2023-01-03
- Android Compose自定义TextField实现自定义的输入框 2023-05-13
- Android开发Compose集成高德地图实例 2023-06-15
- iOS开发 全机型适配解决方法 2023-01-14
- iOS开发使用XML解析网络数据 2022-11-12
- iOS Crash常规跟踪方法及Bugly集成运用详细介绍 2023-01-18
- Flutter进阶之实现动画效果(三) 2022-10-28
- MVVMLight项目Model View结构及全局视图模型注入器 2023-05-07
- iOS中如何判断当前网络环境是2G/3G/4G/5G/WiFi 2023-06-18