首页 > 解决方案 > 后台位置更新 BroadcastReceiver 未触发

问题描述

尽管 Android 文档强烈坚持不使用后台位置更新,但我的应用确实需要它们,所以我更新了所有内容以正确请求权限并遵守新规则。现在,一旦获得ACCESS_BACKGROUND_LOCATION许可,我将执行以下操作以从我的初始片段中请求后台位置更新:

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
    )
}

在我的 AndroidManifest 中,我像这样声明 BroadcastReceiver:

<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>

这是我的 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"
    }
}

并且内部的日志指令onReceive()将日志发送到远程记录器(Bugfender)。当我的应用程序处于前台时,一切似乎都正常,我可以看到日志。但是当它在后台时,不再更新。

我仔细检查了许可,我确定当我注册BroadcastReceiver,时ACCESS_BACKGROUND_LOCATION被授予。

我在装有 Android 10 的三星 S9 上运行。

我是不是忘记了什么?在 Fragment 中执行所有这些操作有问题吗?

标签: androidkotlinfusedlocationproviderapi

解决方案


推荐阅读