3

Even though Android documentation insists heavily on not using background location updates, my app really needs them, so I updated everything to request permissions properly and abide by the new rules. Now once I have ACCESS_BACKGROUND_LOCATION permission granted, I do the following to request background location updates from within my initial Fragment:

private fun configureBackgroundLocationTracking() {
    fusedLocationClient.requestLocationUpdates(createLocationRequest(), getPendingIntent())
}

private fun createLocationRequest(): LocationRequest {
    return LocationRequest.create().apply {
        interval = 20000
        fastestInterval = 10000
        priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
    }
}

private fun getPendingIntent(): PendingIntent {
    val intent = Intent(requireContext(), LocationUpdatesBroadcastReceiver::class.java)
    return PendingIntent.getBroadcast(
        requireContext(),
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT
    )
}

In my AndroidManifest, I declare the BroadcastReceiver like so:

<receiver android:name=".LocationUpdatesBroadcastReceiver"
            android:exported="true"
            android:permission="android.permission.ACCESS_BACKGROUND_LOCATION">
    <intent-filter>
        <action android:name="com.herontrack.LOCATION_UPDATE" />
    </intent-filter>
</receiver>

And here is the code of my LocationUpdatesBroadcastReceiver:

class LocationUpdatesBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val result = LocationResult.extractResult(intent)
        if (result != null) {
            val location = result.lastLocation
            if (location != null) {
                Log.d(TAG, "Received location update: $location")
            }
        }
    }

    companion object {
        private const val TAG = "LUBroadcastReceiver"
    }
}

And the log instruction inside onReceive() sends the log to a remote logger (Bugfender). When my app is in the foreground, everything seems to work, I can see the logs. But when it is in the background, no more updates.

I double checked the permission and I'm sure that when I register the BroadcastReceiver, ACCESS_BACKGROUND_LOCATION is granted.

I'm running on a Samsung S9 with Android 10.

Did I forget something? Is there a problem with doing all of that from within a Fragment?

Sebastien
  • 3,583
  • 4
  • 43
  • 82

1 Answers1

0

Update the flags PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT when creating pending intent broadcastReceiver.

i had the same issue. for background location updates latest android need to show notification

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 29 '23 at 06:06