How do I keep the screen on in my App? [duplicate]

2019-01-02 20:16发布

This question already has an answer here:

For my Android app I never want the phone to lock or the back light to turn off

标签: android
12条回答
旧人旧事旧时光
2楼-- · 2019-01-02 20:24

Don't Use Wake Lock.

It requires permission and other stuff and may cause error if you forget to set it in right time.

The easiest way is to use the below code when you want to keep your screen on..

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

One addition to the answer if you want to remove or terminate keep_Screen_on

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

you can also see here..

And the best and easiest way .. Using android:keepScreenOn="true" in layout root of your activity does the same thing without extra code. But it will remain it in Keep_Scree_on State..

It can be vary on your demand See here

查看更多
情到深处是孤独
3楼-- · 2019-01-02 20:24

You can simply use setKeepScreenOn() from the View class.

查看更多
皆成旧梦
4楼-- · 2019-01-02 20:24

No need to add permission and do tricks. Just use below text in your main layout.

  android:keepScreenOn="true"
查看更多
柔情千种
5楼-- · 2019-01-02 20:26

Use PowerManager.WakeLock class inorder to perform this. See the following code:

import android.os.PowerManager;

public class MyActivity extends Activity {

    protected PowerManager.WakeLock mWakeLock;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle icicle) {
        setContentView(R.layout.main);

        /* This code together with the one in onDestroy() 
         * will make the screen be always on until this Activity gets destroyed. */
        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();
    }

    @Override
    public void onDestroy() {
        this.mWakeLock.release();
        super.onDestroy();
    }
}

Use the follwing permission in manifest file :

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

Hope this will solve your problem...:)

查看更多
ら面具成の殇う
6楼-- · 2019-01-02 20:26

At this point method

final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();

is deprecated.

You should use getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); and getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

查看更多
姐姐魅力值爆表
7楼-- · 2019-01-02 20:30
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

getWindow is a method defined for activities, and won't require you to find a View first.

查看更多
登录 后发表回答