53

My WakeLock isn't keeping my device awake.

In OnCreate() I've got:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My Tag");
mWakeLock.acquire();

then:

new CountDownTimer(1320000, 200) {

    public void onTick(long millisUntilFinished) {
        // I update a progress bar here.                                         
    }

    public void onFinish() {
        // I finish updating the progress bar.
        mWakeLock.release();
    }
}.start();

The screen turns off before the timer finishes, how can I make the screen stay visible?

mWakeLock is a field previously declared like so:

private PowerManager.WakeLock mWakeLock;

My device uses Android 1.6. I would really appreciate any help to resolve this.

Curyous
  • 8,716
  • 15
  • 58
  • 83

14 Answers14

110

WakeLock doesn't usually cause Reboot problems. There may be some other issues in your coding. WakeLock hogs battery heavily, if not released after usage.

WakeLock is an Inefficient way of keeping the screen on. Instead use the WindowManager to do the magic. The following one line will suffice the WakeLock. The WakeLock Permission is also needed for this to work. Also this code is more efficient than the wakeLock.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

You need not relase the WakeLock Manually. This code will allow the Android System to handle the Lock Automatically. When your application is in the Foreground then WakeLock is held and else android System releases the Lock automatically.

Try this and post your comment...

Gringo Suave
  • 29,931
  • 6
  • 88
  • 75
  • I don't think you need the wake lock permission to do it the WindowManager way. – Karu Sep 20 '11 at 08:21
  • WOW! i have used the powermanager to acquire the wakelock in lots of apps, which has given me loads of problems! This is a much efficient way! thanks @AndroidKid ! – udiboy1209 Jul 08 '12 at 04:51
  • Yes, but does FLAG_KEEP_SCREEN_ON allow the screen to dim? – IgorGanapolsky Jan 02 '13 at 13:25
  • 5
    WindowManager.LayoutParams – austin Mar 14 '13 at 03:22
  • doesn't keep my screen on when i click my powerbutton though. – bofredo Aug 30 '13 at 14:00
  • Does this call have to be made in the oncreate() method? Can I call it just before a long loop to ensure the screen stays on? – Fra Aug 05 '15 at 19:48
  • 2
    I doubt whether `FLAG_KEEP_SCREEN_ON` and wake lock are same, coz both have separate functionality like keeping screen on and keeping CPU on(while screen is off). May be as mentioned [here](https://developer.android.com/training/scheduling/wakelock.html). – kAmol Aug 06 '15 at 02:02
  • 1
    @kamol the person wanted to keep the screen on until some task is finished, hence the use of keep screen instead of wakelock. simple to code and managed automatically. – Anoop Chandrika HarisudhanNair Aug 21 '15 at 16:06
  • 1
    @Fra yes you can call this method in any foreground-thread ie) threads that are capable to change the UI elements – Anoop Chandrika HarisudhanNair Aug 21 '15 at 16:07
50

Do you have the required permission set in your Manifest?

<uses-permission android:name="android.permission.WAKE_LOCK" />
wf.
  • 1,013
  • 1
  • 10
  • 13
  • Indeed. Check your logcat output at the time you call the wakelock. The system usually warns you of missing permissions. – Christopher Orr Jan 11 '10 at 13:54
  • I do have those permissions set, and the Android OS mentions the permissions when I install the app. – Curyous Jan 11 '10 at 22:35
  • 1
    I'm just guessing, but another thing to check is that at the time you created the wake lock, the screen has not already turned itself off. For acquire() only guarantees preserving/restoring the power state at the time the wake lock was created. After all: from your problem description, we cannot be sure the screen was still on/visible at the time you called CountDownTimer.start(). – Matt J. Feb 11 '11 at 03:16
  • 1
    +1 because this is what people are looking for when they Google "android wake lock permission" :) – Kezz Mar 23 '13 at 13:56
24

You just have to write this:

 private PowerManager.WakeLock wl;

    protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNjfdhotDimScreen");
    }//End of onCreate

            @Override
        protected void onPause() {
            super.onPause();
            wl.release();
        }//End of onPause

        @Override
        protected void onResume() {
            super.onResume();
            wl.acquire();
        }//End of onResume

and then add permission in the manifest file

 <uses-permission android:name="android.permission.WAKE_LOCK" />

Now your activity will always be awake. You can do other things like w1.release() as per your requirement.

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
Maverick
  • 3,053
  • 6
  • 24
  • 30
10

Keep the Screen On

First way:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Second way:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

Keep the CPU On:

<uses-permission android:name="android.permission.WAKE_LOCK" />

and

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();

To release the wake lock, call wakelock.release(). This releases your claim to the CPU. It's important to release a wake lock as soon as your app is finished using it to avoid draining the battery.

Docs here.

QED
  • 9,803
  • 7
  • 50
  • 87
Ucdemir
  • 2,852
  • 2
  • 26
  • 44
7

Add permission in AndroidManifest.xml, as given below

<uses-permission android:name="android.permission.WAKE_LOCK" />

preferably BEFORE your <application> declaration tags but AFTER the <manifest> tags, afterwards, try making your onCreate() method contain only the WakeLock instantiation.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My Tag");
}

and then in your onResume() method place

@Override
public void onResume() {
   mWakeLock.aquire();
}

and in your onFinish() method place

@Override
public void onFinish() {
   mWakeLock.release();
}
Ajith Ramesh
  • 195
  • 14
CharlesAE
  • 907
  • 12
  • 16
  • What if i want to use wake lock in my service? Can i use wake lock inside service or not? I am starting service from manifest. – krishnamurthy Jun 25 '18 at 05:21
6

To achieve the same programmatic you can use following

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

or adding following in layout also will perform the above task

 android:keepScreenOn="true"

The details you can get from following url http://developer.android.com/training/scheduling/wakelock.html

I have used combination of following to wake my screen when keyguard locked and keep my screen on

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
2

Thank you for this thread. I've been having a hard time implementing a Timer in my code for 5 minutes to run an activity, because my phone I have set to screen off/sleep around 2 minutes. With the above information it appears I have been able to get the work around.

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

    /* Time Lockout after 5 mins */
    getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

       public void run() {

        Intent i = new Intent(AccountsList.this, AppEntryActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        finish();
        return;

       }

    }, 300000); 
    /* Time Lockout END */
 }
2

sample code snippet from android developers site

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  }

Best Practices for Background Jobs

Sree Rama
  • 1,207
  • 12
  • 25
2

I am having a similar problem. I can get the screen to stay on, but if I use a partial wake lock and the screen is turned off, my onFinish function isn't called until the screen is turned on.

You can check your wake lock using mWakeLock.isHeld(), first of all, to make sure you're getting it. Easiest way is to add that to the code, set a breakpoint on it in the debugger, and then check it.

In my case, I'm getting it, but the partial wake lock doesn't seem to be doing anything. Here's my working code for the screen dim lock.

protected void setScreenLock(boolean on){
        if(mWakeLock == null){
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
                                        PowerManager.ON_AFTER_RELEASE, TAG);
        }
        if(on){
         mWakeLock.acquire();
        }else{
            if(mWakeLock.isHeld()){
                mWakeLock.release();
            }
         mWakeLock = null;
        }

    }

ADDENDUM:

Droid Eris and DROID users are reporting to me that this DOES NOT work on their devices, though it works fine on my G1. What device are you testing on? I think this may be an Android bug.

Brock Tice
  • 21
  • 2
2
{PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyWakeLock"); 
wakeLock.acquire();}

use this code and don't forget to permit wakelock in android manifest

Vasfed
  • 18,013
  • 10
  • 47
  • 53
Tugadar
  • 1
  • 3
2

Try using the ACQUIRE_CAUSES_WAKEUP flag when you create the wake lock. The ON_AFTER_RELEASE flag just resets the activity timer to keep the screen on a bit longer.

http://developer.android.com/reference/android/os/PowerManager.html#ACQUIRE_CAUSES_WAKEUP

Archit
  • 887
  • 2
  • 10
  • 19
1

Make sure that mWakeLock isn't accidentally cleaned up before you're ready to release it. If it's finalized, the lock is released. This can happen, for example, if you set it to null and the garbage collector subsequently runs. It can also happen if you accidentally set a local variable of the same name instead of the method-level variable.

I'd also recommend checking LogCat for entries that have the PowerManagerService tag or the tag that you pass to newWakeLock.

Matt Tsōnto
  • 1,518
  • 1
  • 15
  • 30
0

Add permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.WAKE_LOCK" />

Then add code in my.xml:

android:keepScreenOn="true"

in this case will never turn off the page! You can read more this

0

If your use-case is making the screen (activity) ON while doing an action, you shouldn't use WakeLock.

The best way to do that is by enabling the flag FLAG_KEEP_SCREEN_ON.

You can do it programmatically:

class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }
}

Or in your application's layout XML file, by using the android:keepScreenOn attribute:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

Keep the screen on


If that's not the case, check these alternative solutions according to your use-case Alternatives to using wake locks

Mahmoud
  • 2,683
  • 1
  • 30
  • 32