To prevent the screen from going off in Android, you can use the FLAG_KEEP_SCREEN_ON
flag in your activity's window.
To do this, you can call the getWindow
method of the Activity
class to get a reference to the activity's window, and then call the addFlags
method of the Window
class to add the FLAG_KEEP_SCREEN_ON
flag.
Here's an example of how you can do this in your activity's onCreate
method:
public class MyActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }
This code will keep the screen on while the activity is visible.
Note that using the FLAG_KEEP_SCREEN_ON
flag will drain the battery faster, so you should use it only when necessary and release it when it is no longer needed. You can use the clearFlags
method of the Window
class to remove the FLAG_KEEP_SCREEN_ON
flag from the activity's window.
Here's an example of how you can do this in your activity's onPause
method:
@Override protected void onPause() { super.onPause(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); }
This code will remove the FLAG_KEEP_SCREEN_ON
flag from the activity.