androidservicegpsfusedlocationproviderapi

android gps location in service off if device sleep


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.


Solution

  • 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