后台位置更新广播接收器未触发

3
尽管Android文档强烈建议不要使用后台位置更新,但我的应用确实需要它们,因此我已更新所有内容以正确请求权限并遵守新规则。现在,一旦我获得了“ACCESS_BACKGROUND_LOCATION”权限,我会在初始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
    )
}

在我的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权限。

我正在Samsung S9上运行Android 10。

我有遗漏吗?从Fragment中执行所有这些是否存在问题?

1个回答

0

目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接