Here's the relevant code:
WindowManager.LayoutParams windowParams = getWindow().getAttributes();
windowParams.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
windowParams.screenBrightness = 0.0f;
getWindow().setAttributes(windowParams);
I also tried setting screenBrightness to 0 (an integer rather than float), as well as the following line I found in a Stack Overflow answer:
this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
No dice. The screen dims, but does not turn off. The above code worked in previous Android versions. I just tested it in an emulator to make sure. Was a new method implemented to control the screen?
Official
way to lock the screen other than... pushing the button... It's likely Google doesn't want developers to have access to things like locking the screen for security reasons. It would be really easy to write a bit of malware that runs in the background and randomly locks the screen. – Crankle