25

Is there any way to disable sleep of android mobile phone when user is in certain activity.

I want to disable screen time out when user is in main activity.

Is there any way to do it? Don't know if it is possible or not?

Amrit Sharma
  • 1,906
  • 8
  • 45
  • 75

5 Answers5

49

Try this.

 @Override
 protected void onCreate(Bundle icicle) 
 {
     super.onCreate(icicle);
     getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
 }
Chirag
  • 56,621
  • 29
  • 151
  • 198
  • 11
    Or, use `android:keepScreenOn="true"` on some widget in the layout, or use `setKeepScreenOn(true)` from Java (called on some `View` in the activity). – CommonsWare Nov 03 '12 at 13:22
7

I am using this:

@Override
protected void onCreate(Bundle icicle) 
{
      super.onCreate(icicle);
      getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

Don't forget to place the permission in the manifest

<uses-permission android:name="android.permission.WAKE_LOCK" />
Skeets
  • 4,476
  • 2
  • 41
  • 67
Ronald Coarite
  • 4,460
  • 27
  • 31
  • I don't think you need to use the WAKE_LOCK permission in the manifest to use [this window flag](http://stackoverflow.com/questions/3723634/how-do-i-prevent-an-android-device-from-going-to-sleep-programmatically). – VinceFior Mar 20 '16 at 01:48
7

Best way just add

android:keepScreenOn="true"

to the parent layout of that activity.

Anuraag Patil
  • 171
  • 3
  • 2
3

If you just want to prevent the sleep mode on a specific View, just call setKeepScreenOn(true) on that View or set the keepScreenOn property to true. This will prevent the screen from going off while the View is on the screen. No special permission required for this.

Amal Dev S I
  • 938
  • 13
  • 18
2

You can use the following code to keep screen on in a certain function as :

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
   //..screen will stay on during this section..
wl.release();

This will get the power service and acquire its attention then release it after your code is done

benka
  • 4,732
  • 35
  • 47
  • 58
MJBLACKEND
  • 121
  • 1
  • 3