2

I want to turn off the screen. So I tried to do it with PowerManager class but it didn't turn off screen.

PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
Eli Zhang
  • 44
  • 1
  • 8
  • Possible duplicate of [Lock or turn off the screen programmatically](https://stackoverflow.com/questions/44679868/lock-or-turn-off-the-screen-programmatically) –  Dec 06 '17 at 20:52
  • Have you added the permission for accessing wake lock? – WoogieNoogie Dec 06 '17 at 20:53

3 Answers3

1

You can turn off screen by overriding system screen turn off time.

First get system turn off time

int defaultTurnOffTime =  Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 60000);

then put your turn off time

Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 1000);

and when the screen turned off, set default turn off time

Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, defaultTurnOffTime);

add below permission

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
Arif Khan
  • 508
  • 5
  • 12
  • Thakns, but the app is crashing. java.lang.SecurityException: com.detect.bait was not granted this permission: android.permission.WRITE_SETTINGS. – Eli Zhang Dec 06 '17 at 21:11
0

It's not clear from the question if you've tried this, but you might need to make sure that you have the in your manifest:

Any application using a WakeLock must request the android.permission.WAKE_LOCK permission in an element of the application's manifest.

Another area that you might look is logcat to see if there is any stack traces or errors being logged, which could provide more context for people to help out.

0

@SuperDev, add the following to your Manifest:

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

This will resolve your app crash.

Hope it helps :)

nyx69
  • 747
  • 10
  • 21