Keep the screen on v4.1.x

3

I have the following code to keep the screen always on:

if (usuario.getTelaLigada()){   
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

It works in version 4.4 and higher. But not in previous ones.

How do I keep the screen switched on in all versions?

Thank you!

    
asked by anonymous 17.12.2015 / 10:37

1 answer

3

A very common practice in Android development is to use PowerManager.WakeLock to do such a task. However, this is not the ideal and most reliable option, since you will need to add more permission on your application just for that.

In addition, if you accidentally (or some other developer on your team) forget to turn it off, you can drain the battery from your user's device.

For this, I recommend that you use the setKeepScreenOn() method inside the View class:

If you are creating some view via code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    View view = getLayoutInflater().inflate(R.layout.driver_home, null);
    view.setKeepScreenOn(true);
    setContentView(v);
}

Or, via xml:

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">

    ...

</RelativeLayout>

NOTE: It does not matter if the keepScreenOn flag is in your main layout, root, or other layout within your views tree, it will work the same way on any component in your xml . The only point is that the visibility of this view must be visible , otherwise it will not work!

    
18.12.2015 / 02:20