如何取消 Android 的 Places SDK 查找自动完成预测任务?

How to cancel Places SDK for Android find autocomplete predictions task?

我正在尝试弄清楚如何取消使用 Android 的新 Places SDK 获取自动完成预测而创建的任务。

任务是使用此代码创建的 -

Places.initialize(applicationContext, ApiClient.GOOGLE_API_KEY)
placesClient = Places.createClient(this)

placesClient.findAutocompletePredictions(request).addOnSuccessListener { response ->

   for (prediction in response.autocompletePredictions) {
        Log.i(TAG, prediction.placeId)
        Log.i(TAG, prediction.getPrimaryText(null).toString())
    }


}.addOnFailureListener { exception ->
    if (exception is ApiException) {
        val apiException = exception as ApiException
        Log.e(TAG, "Place not found: " + apiException.statusCode)
    }
}

该任务有一个 addOnCancelledListener 但无法取消它!

如何取消这个任务?

您可以使用 getCancellationToken () 方法取消任何 yet-to-be-executed 请求。

您可以从以下link关注官方places sdk文档。 https://developers.google.com/places/android-sdk/reference/com/google/android/libraries/places/api/net/FindAutocompletePredictionsRequest#getCancellationToken()

关于如何使用取消令牌的示例:

https://developers.google.com/android/reference/com/google/android/gms/tasks/CancellationToken

这是取消@Riyasa 分享的链接后的自动完成搜索请求的完整代码

/* 
Create a new CancellationTokenSource object each time you execute a new query 
because the cancellation token received from this will work only for this request 
and not afterwards 
*/

val cancellationTokenSource = CancellationTokenSource()

val requestBuilder = FindAutocompletePredictionsRequest.builder()
        .setQuery(newText) //NewText is your query text
        .setCancellationToken(cancellationTokenSource.token)
//Setting the cancellation token from the object created above

placesClient.findAutocompletePredictions(requestBuilder.build()).addOnSuccessListener { response ->
   //Do what you need to with the result
}

//and finally call this to cancel the request using the object created for this request
cancellationTokenSource.cancel()