首页 > 解决方案 > 成功和失败侦听器方法是否在后台线程上完成?

问题描述

使用成功和失败侦听器的方法是在主 UI 线程还是后台线程上完成的?

例如,我使用的是Google Places SDK。获取地点:

// 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()在后台线程中完成?

标签: javaandroidgoogle-places

解决方案


啊,我做了一些挖掘,这就是我想出的。

placesClient.fetchPlace(...)返回一个任务

任务定义

这对我们来说意味着你可以将它连接到不同的监听器,并在该状态被击中时得到一个 ping。在您选择的特定addOnSuccessListener(...)方法的情况下,这是文档告诉我们的内容:

addOnSuccessListener(...) 定义

所以基本上,在你的代码片段中,获取将在主线程之外完成,然后结果将被传递回主线程。


推荐阅读