且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不推荐使用的 Android API 替代方案

更新时间:2023-01-23 12:53:28

Google Places SDK for Android 已弃用,因此我们需要针对 Places API 进行迁移.要使用新的 Places API 实现 AutoComplete Place.. 请按照以下步骤操作.

Google Places SDK for Android is Deprecated, so we need to migrate for Places API. For implementing AutoComplete Place using new Places API.. please follow below steps.

首先在开发者控制台中启用 PlacesAPI,然后通过在 gradle 中更新来安装客户端库.

First enable PlacesAPI in developer console, then install Client Library by updating in gradle.

(注意:您只能安装客户端库或兼容性库,而不是两者)

(Note: You can only install either the client library or the compatibility library, NOT both)

implementation 'com.google.android.libraries.places:places:1.0.0'

现在在 Oncreate() 中初始化下面的代码;

Now initialize below code inside Oncreate();

 // Add an import statement for the client library.
    import com.google.android.libraries.places.api.Places;

    // Initialize Places.
    Places.initialize(getApplicationContext(), "***YOUR API KEY***");

   // Create a new Places client instance.
   PlacesClient placesClient = Places.createClient(this);

新 PlacesAPI 已初始化..

New PlacesAPI is initialised..

对于自动完成位置使用以下代码(您也可以使用自动完成片段)

For AutoComplete places use below code (You can use AutoComplete Fragment also)

// Set the fields to specify which types of place data to return.
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(
        AutocompleteActivityMode.FULLSCREEN, fields)
        .build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);
            Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
        } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
            // TODO: Handle the error.
            Status status = Autocomplete.getStatusFromIntent(data);
            Log.i(TAG, status.getStatusMessage());
        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }
}

  • 确保清单中的权限
  • API 密钥已生成.
  • 在开发控制台中启用了 Places API.
  • 删除(如果您添加了)

implementation 'com.google.android.gms:play-services-places:16.0.0'

必需的头文件

import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.AutocompleteActivity;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;

希望这会有所帮助..