Search code examples
androidwakelock

Wakelock not working on Android


I am doing a Android app similar to Runkeeper. When I start the app I start a thread for the clock, and I also have onLocationChanged updates for gps. Everything works fine when the screen is on, but when the screen is off the clockthread stops.

I have tried with PARTIAL_WAKE_LOCK but nothing happened. Here is the the code from the manifest.

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

and here is the code

PowerManager.WakeLock wl;

and in onCreate()

PowerManager pm=(PowerManager)this.getSystemService(Context.POWER_SERVICE);
    wl=pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"my wakelock");
    wl.acquire();

have also tried

PowerManager pm=(PowerManager)Context.getSystemService(Context.POWER_SERVICE);
    wl=pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"my wakelock");
    wl.acquire();

I don't know why the the clockthread is stopped when I have WAKE_LOCK. The clockthread is started when I press a button in a butttonlistener if that can be a part of a explenation? Anyone have any suggestions Thanks


Solution

  • I think you misunderstand what a Wakelock does. A wakelock keeps the device active (think CPU running) while your program holds it. Here are some things it doesn't do:

    • Control the lifecycle of any thread in your application process
    • Control the lifecycle of your application!!

    In fact, Android is absolutely guaranteed to stop your application, eventually, no matter what you do. When that happens, you disconnect from the PowerManager and your wakelock is automatically released.

    You might want the AlarmManager.