Search code examples
androidreleasewakelock

releasing wakelock in different activity to where it was acquired


I have two activitys in my app. The first activity acquires a wakelock that is still present even when this activity is destroyed. This activity also sets an alarm whcih starts the second activity. I want the second activity to release the wakelock that was acquired by the first activty.

So bassically:

First activity acquires wakelock >> First activity is destroyed >> Wakelock still acquired >> canender (alarm) opens a new activity (Second Activity) >> Second activity releases wakelock??

The question is how do i release a wakelock in a different activity to where the wakelock has been acquired?

This is the code i am using to acquire the wakelock in the first activity:

    WakeLock wl;
    PowerManager pM = (PowerManager)getSystemService(Context.POWER_SERVICE);
    wl = pM.newWakeLock(PowerManager.FULL_WAKE_LOCK, "wakeLock");
   wl.acquire();

Is there any code i could use to release the wakelock in the second activty?


Solution

  • Store the wake lock in a static variable that both activities can access it. Like this:

    class Globals {
        public static WakeLock wakelock;
    }
    

    In your first activity:

    PowerManager pM = (PowerManager)getSystemService(Context.POWER_SERVICE);
    WakeLock wl = pM.newWakeLock(PowerManager.FULL_WAKE_LOCK, "wakeLock");
    wl.acquire();
    Globals.wakelock = wl; // Save in a place where it won't go
    

      // away when this Activity is done

    In your second activity:

    if (Globals.wakelock != null) {
        Globals.wakelock.release();
        Globals.wakelock = null; // We don't have a wake lock any more
    }