How to leave the screen always on with the app open?

Asked

Viewed 3,070 times

3

I would like to know how to make the screen is turned on without locking while my app is open.

2 answers

3

The best way to do that is to use the FLAG_KEEP_SCREEN_ON in his Activity (and only in a Activity, never on a service or other application component). For example:

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  }

The advantage of this approach is that it does not require special permission, and the platform correctly manages the user by moving between applications, without your application needing to worry about releasing unused features.

Another way to implement this is in your application’s layout XML file, using the attribute android:keepScreenOn :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

Using the android:keepScreenOn="true" is equivalent to using FLAG_KEEP_SCREEN_ON.

You can use any approach that is best for your app.

The advantage of setting programmatically in your Activity is that you offers the option to switch off the screen via code.

SOURCE

2

Before setContentView() use :

  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

There is a better way that it would be an attribute in the.xml layout but I don’t remember at the moment

  • Thank you Adliano Alves, I will test this code in the project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.