Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Java : Turn screen Off

I am making an application that turn the screen ON and OFF with the proximity sensor. The proximity code is finished, but i got trouble using the screen controls.

I have read that I should use,

PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
manager.goToSleep(int amountOfTime);

For that, I need to grant special permissions in order to make it works, but I haven't figured out how to do it.

Also, I have read about changing screen brightness

WindowManager.LayoutParams params = getWindow().getAttributes();
            params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
            params.screenBrightness = 0;
            getWindow().setAttributes(params);

But this way only turn the screen off on my application; it doesn't work if my application is running in background.

I have also read about using Wakelock (i use them to wake my phone from screen-off), but when

PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");
wl.acquire();
wl.release();

But when I do that, nothing happens.

Is there any other way to do it ?

like image 531
Bertrand Avatar asked Nov 04 '22 05:11

Bertrand


1 Answers

You need to give your App the right permissions to do that:

Add <uses-permission android:name="android.permission.DEVICE_POWER" /> to your Manifest inside the <manifest> Tag

If you want to keep your Screen on use this, as suggested by Dianne Hackborn on Google Plus: KeepScreenOn

like image 171
Thommy Avatar answered Nov 07 '22 22:11

Thommy