How to prevent automatic screen lock on android by

2019-02-02 07:54发布

In my app there is a long loading process, and if the devices puts on the screen lock, my process stops for some reason.

How can i prevent the device from automatic screen lock?

7条回答
该账号已被封号
2楼-- · 2019-02-02 08:05

The following line allows your phone to be ON when the app is in foreground

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

The following instructions allow us to disable the lock screen when lock button is pressed. KeyguardLock class was deprecated in API level 13

/*onCreate*/
KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); // Deprecated :/
lock.disableKeyguard();

And in your manifest:

<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
查看更多
We Are One
3楼-- · 2019-02-02 08:11

Another way to keep the screen lock on without having to request the permission in the manifiest is:

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

Are you doing your long loading process in the UI thread? Something doesn't seem right - if the process is so long that the screen lock timesout and your process ends, perhaps it needs to go in a background service.

查看更多
The star\"
4楼-- · 2019-02-02 08:17
KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();

in androidmanifest:

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

OR

Follow this link

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-02-02 08:19

XML Way:

Just use keepScreenOn attribute in your parent layout:

<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:keepScreenOn="true">

programmatically:

You can set it programmatically by adding flag:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
查看更多
一夜七次
6楼-- · 2019-02-02 08:21

one interesting option that wasn't mentioned yet is the

View#setKeepScreenOn(boolean onOff)

method. This can actually be used dynamically at any point during the runtime of the app, e.g. for setting the screen mode depending on the app state

查看更多
欢心
7楼-- · 2019-02-02 08:29

Go with the key guard code its working perfectly,

Just Paste the code in onCreate Method in your mainactivity file And Permission in android manifest file

查看更多
登录 后发表回答