Confirm that the app needs to keep the screen turned on like a game or video app. The best way to do this is to use flag_keep_screen_on in your activity. (and only in an activity, never in a service or other app component).
For example:
publicclassmainactivityextendsactivity{
@Override
Protectedvoid onCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
GetWindow (). Addflags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
The benefit of this approach is that unlike wakelocks (which we'll explore in the Keep the CPU on article), it doesn't require specific permissions, and in the case of different application operations, the system will manage without worrying about unused resources that have not been freed.
Another way: In an XML file, use the Android:keepscreenon property.
< RELATIVELAYOUT
xmlns: Android= "http://schemas.android.com/apk/res/android"
android:layout_width=" match_parent "
android:layout_height=" match_parent "
android:keepscreenon=" true ">
</RELATIVELAYOUT>
This setting android:keepscreenon= "true" is equivalent to flag_keep_screen_on. Whichever way you use the above, it is the best. The advantage of setting flag in activity is that it clears the flag so that the screen can be turned off.
Note: You do not need to clear the FLAG_KEEP_SCREEN_ON flag unless you no longer need to stay on the screen when you run the app. When the application enters the background or returns to the foreground, the window manager is responsible for ensuring normal event handling, but if you explicitly want to clear the Peugeot and allow the screen to go out, you can use Clearflags ().
As follows:
GetWindow (). Clearflags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON).
author has words: If you need android Chinese API, sweep the following QR code, the Android industry in the conscience of choice.
How does Android keep the screen lit?