Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WakeLock

Tags:

android

wakeup

I have a problem with acquiring a WakeLock. It seems not to work. I am trying to acquire a FULL_WAKE_LOCK but neither the display gets enabled nor is my app able to perform tasks.

I am using the following permission: android.permission.WAKE_LOCK

My acquire code looks like this:

PowerManager pm = (PowerManager) getBaseContext().getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "My Tag");
wl.acquire();

What am i doing wrong?

Edit: Added another flag ACQUIRE_CAUSES_WAKEUP ... but no changes in behavior

Edit2: All i am trying to do is, to play music and to wake my device up upon a certain event. The music is working perfectrly but the device stays black.

like image 948
Coxer Avatar asked Sep 01 '10 06:09

Coxer


3 Answers

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 efficient than the wakeLock.

getWindow().addFlags(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.

But if you do want to release the flag, you can do it with:

getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
like image 110
Anoop Chandrika HarisudhanNair Avatar answered Sep 21 '22 13:09

Anoop Chandrika HarisudhanNair


private static PowerManager.WakeLock lockStatic = null;
private static String LOCK_NAME_STATIC = "MyWakeLock";

public static void acquireStaticLock(Context context) {
    getLock(context).acquire();
}

synchronized private static PowerManager.WakeLock getLock(Context context) {
    if (lockStatic == null) {
        PowerManager mgr = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        lockStatic = mgr.newWakeLock(PowerManager.FULL_WAKE_LOCK,
                LOCK_NAME_STATIC);
        lockStatic.setReferenceCounted(true);
    }

    return (lockStatic);
}

Usage:

Call acquireStaticLock() when you need to acuire the lock

Call getLock(this).release(); inside activity when you need to release the lock

Also add permission in minifest file:

<uses-permission android:name="android.permission.WAKE_LOCK" />
like image 40
ramindu Avatar answered Sep 18 '22 13:09

ramindu


Where are you acquiring the wake lock? You will need to acquire it in the receiver of the intent, not in the service/activity that your intent starts.

like image 32
Nic Strong Avatar answered Sep 18 '22 13:09

Nic Strong