迁移到 GoogleApi 客户端

11.2.0 版 Google Play 服务 SDK 包含一种访问 Places SDK for Android 的新方式。GoogleApi 客户端比其前身 (GoogleApiClient) 更易于使用,因为它会自动管理与 Google Play 服务的连接。这样可以减少应用中的样板代码量,并且有助于消除许多常见误区。新版 API 进行了多项改进:

  • 连接过程由系统自动管理,因此新 API 的实现工作量更少。
  • API 调用现在会自动等待服务连接建立,因此在发出请求之前无需等待 onConnected
  • Tasks API 可让您更轻松地编写异步操作。
  • 该代码是独立的,可以轻松移至共享实用程序类或类似工具类中。

更新应用以使用 GoogleApi 客户端需要对 Places SDK for Android 实现进行一些更改。本指南介绍了 Places SDK for Android 的变更,并推荐了在更新应用以使用新客户端时应采取的步骤。

概览

主要的变更如下:

  • 有两个新的入口点:GeoDataClientPlaceDetectionClient。您的应用现在必须同时实例化 GeoDataClientPlaceDetectionClient,而不是创建一个 GoogleApiClient 实例来涵盖所有 API。
  • 由于不再需要连接回调,因此您可以放心地重构应用以将其移除。
  • 新的 Places API 方法现在是异步的,会返回 Task,而不是 PendingResult

加载 Places API

要加载 Places API,请声明入口点,然后在 Fragment 或 Activity 的 onCreate() 方法中实例化客户端,如以下示例所示:

// The entry points to the Places API.
private GeoDataClient mGeoDataClient;
private PlaceDetectionClient mPlaceDetectionClient;

...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Construct a GeoDataClient.
    mGeoDataClient = Places.getGeoDataClient(this, null);

    // Construct a PlaceDetectionClient.
    mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);

比较

新的 Places API 方法现在是异步的,会返回 Task,而不是 PendingResult。数据结构没有更改,因此现有的用于处理结果的代码不需要更新。以下代码示例比较了新旧版本的 GetCurrentPlace()

新方式

Task<PlaceLikelihoodBufferResponse> placeResult = mPlaceDetectionClient.getCurrentPlace(null);
placeResult.addOnCompleteListener(new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
    @Override
    public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse> task) {
        PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();
        for (PlaceLikelihood placeLikelihood : likelyPlaces) {
            Log.i(TAG, String.format("Place '%s' has likelihood: %g",
                placeLikelihood.getPlace().getName(),
                placeLikelihood.getLikelihood()));
        }
        likelyPlaces.release();
    }
});

传统方式

PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
    .getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
  @Override
  public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
    for (PlaceLikelihood placeLikelihood : likelyPlaces) {
      Log.i(TAG, String.format("Place '%s' has likelihood: %g",
          placeLikelihood.getPlace().getName(),
          placeLikelihood.getLikelihood()));
    }
    likelyPlaces.release();
  }
});

了解详情

详细了解如何访问 Google API