英文:
Are success and failure listener methods done on a background thread?
问题
方法使用成功和失败监听器是在主UI线程还是后台线程上执行的?
例如,我正在使用Google Places SDK。要获取一个地点:
// 定义一个地点ID。
final String placeId = "插入地点ID";
// 指定要返回的字段。
final List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// 构造一个请求对象,传递地点ID和字段数组。
final FetchPlaceRequest request = FetchPlaceRequest.newInstance(placeId, placeFields);
placesClient.fetchPlace(request).addOnSuccessListener((response) -> {
Place place = response.getPlace();
Log.i(TAG, "找到地点:" + place.getName());
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
final ApiException apiException = (ApiException) exception;
Log.e(TAG, "未找到地点:" + exception.getMessage());
final int statusCode = apiException.getStatusCode();
// TODO:处理具有给定状态代码的错误。
}
});
fetchPlace()
是在后台线程中执行的吗?
英文:
Are methods using success and failure listeners done on the main UI thread, or a background thread?
For example, I'm using the Google Places SDK. To fetch a place:
// Define a Place ID.
final String placeId = "INSERT_PLACE_ID_HERE";
// Specify the fields to return.
final List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Construct a request object, passing the place ID and fields array.
final FetchPlaceRequest request = FetchPlaceRequest.newInstance(placeId, placeFields);
placesClient.fetchPlace(request).addOnSuccessListener((response) -> {
Place place = response.getPlace();
Log.i(TAG, "Place found: " + place.getName());
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
final ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + exception.getMessage());
final int statusCode = apiException.getStatusCode();
// TODO: Handle error with given status code.
}
});
fetchPlace()
is done in a background thread?
答案1
得分: 0
以下是您要翻译的内容:
啊,我进行了一些调查,这是我得出的结论。
placesClient.fetchPlace(...)
返回一个 Task:
对我们来说,这意味着您可以将它连接到各种侦听器,并在达到该状态时收到通知。在您选择了特定的 addOnSuccessListener(...)
方法的情况下,以下是文档告诉我们的内容:
因此,基本上,在您的代码片段中,获取将在主线程之外完成,然后将结果传递回主线程。
英文:
Ah, I did some digging and here's what I came up with.
placesClient.fetchPlace(...)
returns a Task:
What that means for us right here is that you can hook it up to various listeners and get a ping whenever that state is hit. In your case with that specific addOnSuccessListener(...)
method you picked, here's what the docs tell us:
So basically, in your snippet the fetching will be done off the main thread, and then the results will be delivered back to the main thread.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论