Search code examples
androidservicelocation

onLocationChanged is called too late when my App is in background


I am getting location updates in a service. OnLocationChange is called within seconds when my app is in Foreground. But when it is in Background, it is called after a few minutes.. What is the problem? and what is the solution? I am not stopping my service when going in background.


Solution

  • I found the issue. Android has added limitations to Location updates from 8.0 onwards here:

    "In an effort to reduce power consumption, Android 8.0 (API level 26) limits how frequently background apps can retrieve the user's current location. Apps can receive location updates only a few times each hour."

    Solution: you need to start Foreground Service, which requires to show notification, like:

    Intent notificationIntent = new Intent(this, ExampleActivity.class);
    PendingIntent pendingIntent =
            PendingIntent.getActivity(this, 0, notificationIntent, 0);
    
    Notification notification =
              new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
        .setContentTitle(getText(R.string.notification_title))
        .setContentText(getText(R.string.notification_message))
        .setSmallIcon(R.drawable.icon)
        .setContentIntent(pendingIntent)
        .setTicker(getText(R.string.ticker_text))
        .build();
    
    startForeground(ONGOING_NOTIFICATION_ID, notification);