2

I need to update the location through GPS/Network in the background even when the phone is in sleep.
I implement android service to archive that goal. But the problem is when I put device in sleep, i notify that the GPS ICON in notification bar gone away as location update not working anymore.

How can I keep GPS/Network location update in such circumstance?

P/S: I use FusedLocationAPI and foreground service. Thanks in advance.
Please note that GPS-ICON image only mention icon in notification bar, I still keep GPS provider turn on.

Robert
  • 5,278
  • 43
  • 65
  • 115
Vinh.TV
  • 299
  • 3
  • 17

1 Answers1

5

You should aquire a wake lock:

    //in onCreate of your service
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    cpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "gps_service");
    cpuWakeLock.acquire();

    // Release in onDestroy of your service
    if (cpuWakeLock.isHeld())
      cpuWakeLock.release();

and add this to your manifest:

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

Above is good if you need continuous location updates, but if you need locations only from time to time then look into: https://github.com/commonsguy/cwac-locpoll

marcinj
  • 48,511
  • 9
  • 79
  • 100
  • I added your code with excitement as this looks like it should work. However I stop seeing onLocationChanged() calls as soon as I turn off the screen, and they don't start again until I unlock the screen. – poleguy Jan 18 '17 at 04:48
  • Have you found a solution? – sanevys Jun 14 '23 at 08:21
  • You may try disabling battery optimizations on your device for your app, also do you have foreground service? – marcinj Jun 14 '23 at 16:26