Keep screen on in Activity - does not work with FLAG_KEEP_SCREEN_ON

人走茶凉 提交于 2019-12-21 10:15:12

问题


So, for a long time I thought that I knew how to stop the screen from going into sleep mode, I simply used this code in my Activity:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

However, I realized that this only worked when my phone was in "developer mode", ie when the usb debugging (Settings --> Developer options --> USB debugging) was enabled/checked. Then the above codes indeed stops the screen/device to go to sleep.

When that debugging is not checked, then my screen goes to sleep like there's no tomorrow. I am running Android 4.04 on my device, and

 android:minSdkVersion="12"
 android:targetSdkVersion="16"

Anyone heard about this issue?

EDIT

I have tested with Commonswares suggestion, and added the setKeepScreenOn() to the code, so it looks like this:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
View root = findViewById(android.R.id.content); 
if (root != null)
    root.setKeepScreenOn(true);

I have also checked so that this code is actually executed, and it is. But it doesnt change a thing...


回答1:


i was facing same problem, i was using one activity for my project and all the other screen are fragments then i used the android:keepScreenOn="true" in main activity.

please try to use this and let me know if you didn't get your desire result.

Thanks.




回答2:


Only solution which realy works in my app is WakeLock in main application class. Unfortunately the SCREEN_BRIGHT_WAKE_LOCK flag is deprecated!

public class MyApp extends Application {
    PowerManager.WakeLock screenOnWakeLock;
    @Override
    public void onCreate() {
        super.onCreate();
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock =  powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,"ScreenlockTag");
        wakeLock.acquire();
    }

    @Override
    public void onTerminate()
    {
        if (screenOnWakeLock != null && screenOnWakeLock.isHeld())
            screenOnWakeLock.release();
        super.onTerminate();
    }
}


来源:https://stackoverflow.com/questions/15189767/keep-screen-on-in-activity-does-not-work-with-flag-keep-screen-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!