我正在尝试弄清楚如何取消使用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,但无法取消它!
如何取消此任务?
答案 0 :(得分:1)
这是在@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()
答案 1 :(得分:0)
您可以使用getCancellationToken()方法来取消任何尚未执行的请求。
您可以通过以下链接关注官方场所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