【问题标题】:Kotlin: FusedLocationProviderClient.removeLocationUpdates always return falseKotlin:FusedLocationProviderClient.removeLocationUpdates 总是返回 false
【发布时间】:2021-11-05 15:28:01
【问题描述】:

这个问题似乎与this 重复,但相信我,我已经尝试了解决方案,但无法找出问题背后的原因。我是 Kotlin 的新手,我是 FusedLocationProvider 的 requesting location updates

相关代码:

private lateinit  var mLocationCallback: LocationCallback? = null
private lateinit var mFusedLocationProviderClient: FusedLocationProviderClient
private lateinit var mLocationRequest: LocationRequest

mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(mContext)
// Create a LocationRequest
mLocationRequest = LocationRequest.create().apply {
    interval = java.util.concurrent.TimeUnit.SECONDS.toMillis(1000)
    smallestDisplacement = 0f
    // Sets the fastest rate for active location updates. This interval is exact, and your
    // application will never receive updates more frequently than this value.
    fastestInterval = java.util.concurrent.TimeUnit.SECONDS.toMillis(1000)
    // Sets the maximum time when batched location updates are delivered. Updates may be
    // delivered sooner than this interval.
    maxWaitTime = java.util.concurrent.TimeUnit.MINUTES.toMillis(1000)
    priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}

// Initialize the LocationCallback.
mLocationCallback = object : LocationCallback() {
    override fun onLocationResult(locationResult: LocationResult) {
        super.onLocationResult(locationResult)
        // Normally, you want to save a new location to a database. We are simplifying
        // things a bit and just saving it as a local variable, as we only need it again
        mCurrentLocation = locationResult.lastLocation
        //Get Date Time
        // saveLatLngData(this,mCurrentLocation.latitude.toString(),mCurrentLocation.longitude.toString())
        mTimeStamp = Calendar.getInstance().time
        Log.d(TAG, "LocationCallback=> TimeStamp: " + mDateFormat!!.format(mTimeStamp) + " Latitude: " + mCurrentLocation!!.latitude + " - Longitude: " + mCurrentLocation!!.longitude + " - Altitude: " + mCurrentLocation!!.altitude)
        mNotificationText = mDateFormat!!.format(mTimeStamp) + "\nLat: ${locationResult.lastLocation.latitude} | Long: ${locationResult.lastLocation.longitude}"
        createForegroundInfo()
    }
}

// Subscribe to location changes.
if (ActivityCompat.checkSelfPermission(mContext,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext,Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    if(mFusedLocationProviderClient != null)
    {
        mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest,mLocationCallback,Looper.getMainLooper())
        Log.d(TAG, "startMonitoring: mFusedLocationProviderClient is registered now.")
    }
    else
    {
        Log.d(TAG, "startMonitoring: mFusedLocationProviderClient is not initialized!")
    }
    return
}

//STOPPING LOCATION UPDATES (AFTER GETTING SOME VALUES) USING THE FOLLOWING CODE
if (mFusedLocationProviderClient != null) {
    try {
        val voidTask: Task<Void> = mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback)
        if (voidTask.isSuccessful)
        {
            Log.d(TAG, "stopMonitoring: removeLocationUpdates successful.")
        }
        else
        {
            Log.d(TAG, "stopMonitoring: removeLocationUpdates updates unsuccessful! " + voidTask.toString())
        }
    }
    catch (exp: SecurityException)
    {
        Log.d(TAG, "stopMonitoring: Security exception.")
    }
}

预期行为:

调用mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback) 方法后,位置更新应被删除,stopMonitoring: removeLocationUpdates successful. 应打印在记录器上。

问题:

我在记录器上看到stopMonitoring: removeLocationUpdates updates unsuccessful! 并没有删除位置更新,这意味着else 条件已执行。

我试图找出原因并应用了一些解决方案。请指导我一些可能的选择。

【问题讨论】:

  • 任务是一些未来结果的包装。如果你立即检查它,它几乎可以保证还没有完成。您需要使用它的一种回调方法或在协程中调用await() 来检查它。
  • 是的,在Main调度器上启动一个协程并使用kotlinx-coroutines-play-services中的Task.await。如果不成功会抛出异常。
  • 非常感谢您的指导。由于我刚开始学习 Kotlin,我对此一无所知。是的,我需要先学习基础知识:)

标签: android kotlin location fusedlocationproviderapi


【解决方案1】:

Task 需要一些时间才能完成。您希望它立即完成,这不太可能发生。你应该做这样的检查:

try {
    val voidTask: Task<Void> = mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback)
    voidTask.addOnCompleteListener {
        if(it.isSuccessful) {
            Log.d("Location", "stopMonitoring: removeLocationUpdates successful.")
        } else {
            Log.d("Location", "stopMonitoring: removeLocationUpdates updates unsuccessful! " + voidTask.toString())
        }
    }
} catch (exp: SecurityException){
    Log.d("Location", "stopMonitoring: Security exception.")
}

【讨论】:

  • 感谢您的帮助。我真的很担心这个。你让我开心。
  • @ItbanSaeed 很高兴我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2018-11-05
  • 2019-05-06
  • 2017-04-29
  • 2013-04-30
  • 2015-01-20
  • 2011-09-30
相关资源
最近更新 更多