简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM