我正在尝试弄清楚如何使用Android的新位置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,但无法取消它!
我如何取消此任务?
这是取消自动完成搜索请求的完整代码,遵循@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()
您可以使用getCancellationToken((方法取消任何尚未执行的请求。
您可以从以下链接中遵循官方的SDK文档。https://developers.google.com/places/android-sdk/reference/com/google/google/android/libraries/libraries/places/api/net/net/findautautautautautecomplestepredionsrequestionsrequest#getcancellation((
如何使用取消令牌:
https://developers.google.com/android/reference/com/google/android/android/gms/tasks/cancellationToken