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!