Android Keep Screen On In App

老子叫甜甜 提交于 2019-11-30 09:35:26

问题


I have an android app which runs a foreground service and while that service is running I would like to give the user the option to keep the screen on.

I added to my settings preferences, a checkbox preference and if true, I would like to keep the screen on but have it set to off by default. It's just something my users have asked for. Currently i have the preference on but when I run the service my screen still shuts of here is what I've done

global variable

private static final String PREFS_DEVICE = "DeviceInfo";

code and if statement

SharedPreferences settings = getSharedPreferences(PREFS_DEVICE, 0);
            if(settings.getBoolean("screenPref", false)) {
                final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
                this.mWakeLock.acquire();
            }

and then i added this to my manifest

<uses-permission android:name="android.permission.WAKE_LOCK" />

Is there something I'm doing wrong. Is there a different way to do this from a service or is it just not possible from a service (hope that's not the case).


回答1:


Try this:

mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,         
                            "");    
mWakeLock.acquire();



回答2:


You might use flag FLAG_KEEP_SCREEN_ON

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

and when you don't want to keep on

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



回答3:


This way is much better, bcz of using less permissions, services and ofc battery:

public void setWakelock(Activity Target, boolean State)
{
    if (State) Target.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    else Target.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    return;
}

EDITED




回答4:


Follow the pattern Mark Murphy provides with the WakefulIntentService. and you can find the explanation in his book very good one



来源:https://stackoverflow.com/questions/7342767/android-keep-screen-on-in-app

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