【问题标题】:Google Places API Error - ApiException: 9008: PLACES_API_INVALID_APPGoogle Places API 错误 - ApiException: 9008: PLACES_API_INVALID_APP
【发布时间】:2018-05-29 07:22:05
【问题描述】:

我想在我的一个 Android 应用程序中使用 Google Places API。但是我收到了这个错误:

com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException:9008: PLACES_API_INVALID_APP

到目前为止我做了什么。

  • 我在 https://console.developers.google.com 中创建了 API 密钥
  • 应用限制中选择了Android应用并添加了包名SHA-1证书指纹。李>
  • 我在AndroidManifest.xml 文件中添加了<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_places_api_key" />
  • 我检查了 3 次以上,我使用了相同的 API 密钥,我在其中添加了 包名称SHA-1 证书指纹强>。
  • 我创建了另一个 API KEY 来检查它是否可以正常工作。我发现当我添加 Package nameSHA-1 证书指纹 时,它会给我上面提到的 ERROR 否则它工作正常。
  • 我也尝试添加 Release SHA-1,但出现同样的错误。

我的代码如下。

EmploymentDetailsActivity.java

    public class EmploymentDetailsActivity extends BaseActivity {


    @BindView(R.id.aet_employment_employer)
    AutoCompleteTextView employerAutoCompleteTextView;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_employment_details);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mGeoDataClient = Places.getGeoDataClient(this);

        final GooglePlacesAdapter adapter = new GooglePlacesAdapter(this);
        employerAutoCompleteTextView.setAdapter(adapter);
        employerAutoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                final AutocompletePrediction item = adapter.getItem(position);
                final String placeId = item.getPlaceId();
                final CharSequence primaryText = item.getPrimaryText(null);

                employerAutoCompleteTextView.setText(primaryText);

                Task<PlaceBufferResponse> placeResult = mGeoDataClient.getPlaceById(placeId);
                placeResult.addOnCompleteListener(mUpdatePlaceDetailsCallback);
            }
        });
    }
}

GooglePlacesAdapter.java

    public class GooglePlacesAdapter extends ArrayAdapter<AutocompletePrediction> implements Filterable {

    private Context mContext;
    private GeoDataClient mGeoDataClient;
    private static final String TAG = "mk";
    private ArrayList<AutocompletePrediction> mResultList;

    public GooglePlacesAdapter(Context context) {
        super(context, android.R.layout.simple_dropdown_item_1line);
        this.mContext = context;
        mGeoDataClient = Places.getGeoDataClient(mContext);
    }

    @Override
    public int getCount() {
        return mResultList.size();
    }

    @Override
    public AutocompletePrediction getItem(int position) {
        return mResultList.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_google_places, parent, false);
        }

        AutocompletePrediction autocompletePrediction = getItem(position);

        TextView placeName = convertView.findViewById(R.id.tv_primary_text);
        TextView placeAddress = convertView.findViewById(R.id.tv_secondary_text);

        placeName.setText(autocompletePrediction.getPrimaryText(null));
        placeAddress.setText(autocompletePrediction.getSecondaryText(null));

        return convertView;
    }

    @Override
    public Filter getFilter() {

        return new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();

                if (constraint != null) {

                    mResultList = getAutocomplete(constraint);

                    if (mResultList != null) {
                        results.values = mResultList;
                        results.count = mResultList.size();
                    }
                }

                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
    }

    private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {

        AutocompleteFilter.Builder filterBuilder = new AutocompleteFilter.Builder();
        filterBuilder.setTypeFilter(AutocompleteFilter.TYPE_FILTER_NONE).setCountry("IN");

        Log.e(TAG, "constraint.toString(): " + constraint.toString());

        Task<AutocompletePredictionBufferResponse> results =
                mGeoDataClient.getAutocompletePredictions(constraint.toString(), null,
                        filterBuilder.build());

        // 60s for a result from the API.
        try {
            Tasks.await(results, 60, TimeUnit.SECONDS);
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            e.printStackTrace();
        }

        try {

            AutocompletePredictionBufferResponse autocompletePredictions = results.getResult();

            // Freeze the results immutable representation that can be stored safely.
            return DataBufferUtils.freezeAndClose(autocompletePredictions);

        } catch (RuntimeExecutionException e) {

            // If the query did not complete successfully return null
            Toast.makeText(getContext(), "Error contacting API: " + e.toString(), Toast.LENGTH_SHORT).show();

            Log.e(TAG, "Error getting autocomplete prediction API call", e);

            return null;
        }
    }
}

AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.xxxxxxxx.xxxxx">

<application
        android:name=".ConsumerApplication"
        android:allowBackup="true"
        android:icon="@mipmap/app_icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/app_icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_places_api_key" />
</application>

</manifest>

strings.xml

<resources>
    <string name="google_places_api_key">AIzxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</string>
</resources>

build.gradle(应用程序)

    dependencies {
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    ext {
        playServicesVersion = '15.0.1'
    }
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.razorpay:checkout:1.4.7'
    compile "com.google.android.gms:play-services-vision:${playServicesVersion}"
    compile "com.google.android.gms:play-services-location:${playServicesVersion}"
    //compile "com.google.android.gms:play-services:${playServicesVersion}"
    compile "com.google.android.gms:play-services-places:${playServicesVersion}"
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'org.apache.commons:commons-lang3:3.4'
    compile 'commons-io:commons-io:2.4'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'com.google.dagger:dagger:2.10'
    compile 'com.jakewharton:butterknife:8.5.1'
    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
    compile 'com.squareup.okio:okio:1.13.0'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.retrofit2:converter-gson:2.0.1'
    compile 'com.android.support:multidex:1.0.1'
    compile 'org.apache.commons:commons-lang3:3.4'
    compile 'com.android.support:design:26.1.0'
    compile 'com.github.arthurghazaryan:floatingactionmenu:1.0.0'
    compile 'com.quiklo.jsonapi.customer:cust-app:1.0'
    compile 'com.quiklo.jsonapi.shared:basic:1.0'
    compile 'com.olmec.smartloan.shared:shared-api:1.0'
    compile 'com.jaredrummler:material-spinner:1.1.0'
    compile 'com.f2prateek.dart:dart:2.0.2'
    compile 'com.f2prateek.dart:henson:2.0.2'
    //    compile 'uk.co.markormesher:android-fab:2.2.2'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.f2prateek.dart:dart-processor:2.0.2'
    annotationProcessor 'com.f2prateek.dart:henson-processor:2.0.2'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.10'
    annotationProcessor 'com.google.guava:guava:19.0'
}
apply plugin: 'com.google.gms.google-services'

如果需要任何详细信息,请告诉我。提前致谢。

【问题讨论】:

  • 您是在生产 apk 中还是在测试中遇到此错误?可能是 SHA 错误
  • 在测试和生产中。奇怪的是,在添加包名称和 SHA-1 指纹时,它给了我错误。第二个奇怪的事情是它只给我这个特定应用程序的错误。我有另一个应用程序,在该应用程序中运行良好。@ParaskevasNtsounos
  • 根据文档,由于不允许应用程序使用 API 密钥而导致的错误。可能未配置 API 密钥,请转到您的 API 控制台并检查 API 密钥 Restrictions 是否允许 Android 应用使用。 /PlacesStatusCodes.html#INVALID_APP
  • 正如我在上面的评论中提到的,问题仍然存在。如果我输入 包名和 SHA-1 指纹,它会给我错误。否则它工作正常。您能否为此提供 Google 群组,我将在其中询问有关此问题的问题 **ISSUE**@Arpanßløødyßadßøy
  • 启用 Android Places Api 。还要检查创建的 SHA-1 是否正确。

标签: android google-play-services google-places-api google-places googleplacesautocomplete


【解决方案1】:

我得到了解决方案。是包名造成了问题。

build.gradle (Module: app) 我有 applicationIdSuffix,当您切换到 mock 版本时,它会更改包名称。

由于包名称会更改,CORRECT SHA-1 指纹也将不起作用。所以,我需要附加 .mock 并将其放入 Google API Console 然后它开始工作。

productFlavors {
    mock {
        versionNameSuffix ":test"
        applicationIdSuffix = ".mock"
        buildConfigField "String", "PING_URL", '"https://demoapps.xxxxxxxxx.com/"'
        signingConfig signingConfigs.ReleaseBuild
    }
    prod {
        buildConfigField "String", "PING_URL", '"https://apps.xxxxxxxxx.com/"'
    }
}

【讨论】:

    【解决方案2】:

    您很可能缺少其中之一

    • 您必须从控制台启用场所 API。
    • 您将键存储为字符串资源。有两种变体 字符串资源 - 调试和发布。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 2022-01-17
      相关资源
      最近更新 更多