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, as you will need to add an extra permission in your application just for this.
Also, if you accidentally (or some other developer of your team) forget to turn it off, you may drain the battery from your user’s device.
For this, I recommend that you use the method setKeepScreenOn()
within the class View
:
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 doesn’t matter if the flag keepScreenOn
is in your main layout, root or other layout within your view tree, will work the same way in any component in your xml
. The only point is that the visibility of this view needs to be as visible
, otherwise it will not work!
Check this out: http://stackoverflow.com/questions/24031838/turning-screen-on-off-android
– user28595