启动活动时出现Google Maps API密钥错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了启动活动时出现Google Maps API密钥错误相关的知识,希望对你有一定的参考价值。

我正在尝试使用android Studio构建一个使用Google地图活动的应用程序。

我面临的问题是:每当我尝试启动活动时,应用程序都会崩溃。当我使用带有SDK 24的模拟器时,活动启动,它需要我的许可,然后它给我一个身份验证错误,即使我放置了正确的API密钥。

在具有SDK 26的模拟器上,活动甚至不会启动,它会立即崩溃。

你能帮忙吗?

MapsActivity

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.util.ArrayList;


@SuppressWarnings("unchecked")
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    @Override
    public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onMapReady: map is ready");
        mMap = googleMap;

        if (mLocationPermissionsGranted) {
            getDeviceLocation();

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);

        }
    }

    private static final String TAG = "MapsActivity";

    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 15f;

    //vars
    private Boolean mLocationPermissionsGranted = false;
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationProviderClient;

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

        getLocationPermission();
    }

    private void getDeviceLocation(){
        Log.d(TAG, "getDeviceLocation: getting the devices current location");

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try{
            if(mLocationPermissionsGranted){

                final Task location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if(task.isSuccessful()){
                            Log.d(TAG, "onComplete: found location!");
                            Location currentLocation = (Location) task.getResult();

                            moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
                                    DEFAULT_ZOOM);

                        }else{
                            Log.d(TAG, "onComplete: current location is null");
                            Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }catch (SecurityException e){
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }

    private void moveCamera(LatLng latLng, float zoom){
        Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
    }

    private void initMap(){
        Log.d(TAG, "initMap: initializing map");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        mapFragment.getMapAsync(MapsActivity.this);
    }

    private void getLocationPermission(){
        Log.d(TAG, "getLocationPermission: getting location permissions");
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                mLocationPermissionsGranted = true;
                initMap();
            }else{
                ActivityCompat.requestPermissions(this,
                        permissions,
                        LOCATION_PERMISSION_REQUEST_CODE);
            }
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: called.");
        mLocationPermissionsGranted = false;

        switch(requestCode){
            case LOCATION_PERMISSION_REQUEST_CODE:{
                if(grantResults.length > 0){
                    for(int i = 0; i < grantResults.length; i++){
                        if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                            mLocationPermissionsGranted = false;
                            Log.d(TAG, "onRequestPermissionsResult: permission failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: permission granted");
                    mLocationPermissionsGranted = true;
                    //initialize our map
                    initMap();
                }
            }
        }
    }

}

带有SDK 24的模拟器的logcat出错:

    06-21 16:52:53.625 13392-13392/com.example.raluca.geoloc.feature E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:52:55.011 1314-1321/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
06-21 16:52:55.452 13392-13560/com.example.raluca.geoloc.feature E/Google Maps Android API: Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
06-21 16:52:55.454 13392-13560/com.example.raluca.geoloc.feature E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
    Ensure that the "Google Maps Android API v2" is enabled.
    Ensure that the following Android Key exists:
        API Key: XXX_Key
        Android Application (<cert_fingerprint>;<package_name>): D3:DF:7B:C7:09:CA:00:9F:32:DD:93:98:D6:E2:09:A1:18:B1:F6:6B;com.example.raluca.geoloc.feature
06-21 16:53:01.866 13392-13392/com.example.raluca.geoloc.feature E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.raluca.geoloc.feature, PID: 13392
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=1234, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
        at android.app.ActivityThread.-wrap20(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
        at com.example.raluca.geoloc.feature.MapsActivity.initMap(MapsActivity.java:110)
        at com.example.raluca.geoloc.feature.MapsActivity.onRequestPermissionsResult(MapsActivity.java:154)
        at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:7067)
        at android.app.Activity.dispatchActivityResult(Activity.java:6919)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096) 
        at android.app.ActivityThread.-wrap20(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6077) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
06-21 16:53:02.076 1314-1322/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
06-21 16:53:05.957 8187-8220/? E/InputDispatcher: channel '65bcf76 com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.LoginActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-21 16:53:05.957 8187-8220/? E/InputDispatcher: channel '23dfb3a com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-21 16:53:26.978 8543-12462/? E/NetworkScheduler: Unrecognised action provided: android.intent.action.PACKAGE_REMOVED
06-21 16:53:27.653 8543-11730/? E/NetworkScheduler: Unrecognised action provided: android.intent.action.PACKAGE_REPLACED
06-21 16:53:28.495 8906-13710/? E/FontsPackageChangeOp: Error adding manifest dependency for newly downloaded font {Press Start 2P, wdth 100.0, wght 400, ital 0.0, bestEffort false}
06-21 16:53:28.507 8906-13053/? E/FontDisk: Error inserting metadata for Press Start 2P
    java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/user/0/com.google.android.gms/databases/metadata.db
        at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1442)
        at vdo.run(Unknown Source)
        at ovb.run(:com.google.android.gms@12685026@12.6.85 (040700-197041431):27)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at pbc.run(:com.google.android.gms@12685026@12.6.85 (040700-197041431))
        at java.lang.Thread.run(Thread.java:761)
06-21 16:53:29.228 13637-13764/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:53:29.611 13637-13764/? E/Finsky: [464] com.google.android.finsky.am.c.a(34): Unable to build selector: /storage/emulated/0/Download/marketenvs.csv (No such file or directory)
06-21 16:53:30.423 13637-13637/? E/Finsky: [1] com.google.android.finsky.wear.y.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
06-21 16:53:35.484 13637-13828/? E/Finsky: [483] com.google.android.finsky.splitinstallservice.ad.a(3): Can't schedule deferred install. No modules found.
06-21 16:53:36.939 13637-13637/? E/Finsky: [1] com.google.android.finsky.wear.y.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
06-21 16:53:37.759 13836-13836/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:53:38.320 8906-8965/? E/AsyncOpDispatcher: Unable to get current module info in ModuleManager created with non-module Context
06-21 16:53:39.373 8543-13891/? E/BluetoothAdapter: Bluetooth binder is null
06-21 16:53:39.503 8543-13891/? E/GCoreUlr: java.lang.IllegalStateException: Missing location or location status: 3016643, -1, 3781840, 7160153
        at awot.a(:com.google.android.gms@12685026@12.6.85 (040700-197041431):387)
        at awos.a(:com.google.android.gms@12685026@12.6.85 (040700-197041431):12)
        at awos.handleMessage(:com.google.android.gms@12685026@12.6.85 (040700-197041431):7)
        at oup.run(:com.google.android.gms@12685026@12.6.85 (040700-197041431):6)
        at ovb.run(:com.google.android.gms@12685026@12.6.85 (040700-197041431):27)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at pbc.run(:com.google.android.gms@12685026@12.6.85 (040700-197041431))
        at java.lang.Thread.run(Thread.java:761)
06-21 16:53:40.868 12038-13901/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:58:10.742 8543-13895/? E/BluetoothAdapter: Bluetooth binder is null
06-21 16:58:10.743 8543-13895/? E/GCoreUlr: java.lang.IllegalStateException: Missing location or location status: 3016643, -1, 3781840, 7431479
        at awot.a(:com.google.android.gms@12685026@12.6.85 (040700-197041431):387)
        at awos.a(:com.google.android.gms@12685026@12.6.85 (040700-197041431):12)
        at awos.handleMessage(:com.google.android.gms@12685026@12.6.85 (040700-197041431):7)
        at oup.run(:com.google.android.gms@12685026@12.6.85 (040700-197041431):6)
        at ovb.run(:com.google.android.gms@12685026@12.6.85 (040700-197041431):27)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at pbc.run(:com.google.android.gms@12685026@12.6.85 (040700-197041431))
        at java.lang.Thread.run(Thread.java:761)
06-21 17:07:17.957 8543-9125/? E/WakeLock: release without a matched acquire!
06-21 17:07:18.371 14053-14083/? E/SQLiteLog: (1) no such table: mmsconfig
06-21 17:07:18.376 14053-14083/? E/Babel_SMS: canonicalizeMccMnc: invalid mccmnc nullnull

带有SDK 26的模拟器的logcat出错:

    06-21 17:13:05.646 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:14.440 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.440 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.441 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.441 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.443 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.899 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:15.787 5360-5360/com.example.raluca.geoloc.feature E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.raluca.geoloc.feature, PID: 5360
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
        at com.example.raluca.geoloc.feature.MapsActivity.initMap(MapsActivity.java:110)
        at com.example.raluca.geoloc.feature.MapsActivity.getLocationPermission(MapsActivity.java:123)
        at com.example.raluca.geoloc.feature.MapsActivity.onCreate(MapsActivity.java:67)
        at android.app.Activity.performCreate(Activity.java:6975)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6541) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
06-21 17:13:16.975 1510-1510/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:16.976 1510-1510/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:16.978 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:16.990 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:16.990 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:16.998 2349-5365/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-21 17:13:17.682 2308-2853/com.google.android.gms.persistent E/ctxmgr: [ProducerStatusImpl]updateStateForNewContextData: inactive, contextName=7
06-21 17:13:17.794 2308-2308/com.google.android.gms.persistent E/BeaconBle: Missing BluetoothAdapter
06-21 17:13:17.895 2308-2308/com.google.android.gms.persistent E/BeaconBle: Scan couldn't start for Places
06-21 17:13:22.074 1510-1650/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:22.074 1510-1650/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:22.074 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:22.084 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:22.084 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:22.086 2349-5365/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-21 17:13:27.115 1510-1648/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:27.116 1510-1648/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:27.116 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:27.123 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:27.124 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:27.714 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:27.737 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:31.070 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:31.084 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:32.154 1510-1650/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:32.155 1510-1650/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:32.155 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:32.157 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:32.157 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.

Msps活动布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MapsActivity"
        android:id="@+id/map"
    class="com.google.android.gms.maps.SupportMapFragment"
        />
</RelativeLayout>

摇篮

android {
    compileSdkVersion 26
    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            debuggable true
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation project(':base')
    testImplementation 'junit:junit:4.12'

    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.github.orhanobut:logger:1.12'
    compile 'com.google.android.gms:play-services-maps:11.6.0'

    implementation "com.google.android.gms:play-services-location:11.6.0"

}
答案

你必须在onCreate()中初始化你的地图就像在这里完成一样,这将完成你的工作。

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback
{

    private GoogleMap mMap;

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
        Log.d("Mapready", "onMapReady: map is ready");
        mMap = googleMap;

        if (mLocationPermissionsGranted)
        {
            getDeviceLocation();

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);

        }
    }

    private static final String TAG = "MapsActivity";

    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 15f;

    //vars
    private Boolean mLocationPermissionsGranted = false;
    private FusedLocationProviderClient mFusedLocationProviderClient;



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

        initMap();

        getLocationPermission();
    }

    private void getDeviceLocation(){
        Log.d(TAG, "getDeviceLocation: getting the devices current location");

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try{
            if(mLocationPermissionsGranted){

                final Task location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if(task.isSuccessful()){
                            Log.d(TAG, "onComplete: found location!");
                            Location currentLocation = (Location) task.getResult();

                            moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
                                    DEFAULT_ZOOM);

                        }else{
                            Log.d(TAG, "onComplete: current location is null");
                            Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }catch (SecurityException e){
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }

    private void moveCamera(LatLng latLng, float zoom){
        Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
    }

    private void initMap(){
        Log.d(TAG, "initMap: initializing map");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        mapFragment.getMapAsync(MapsActivity.this);
    }

    private void getLocationPermission(){
        Log.d(TAG, "getLocationPermission: getting location permissions");
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                mLocationPermissionsGranted = true;
                initMap();
            }else{
                ActivityCompat.requestPermissions(this,
                        permissions,
                        LOCATION_PERMISSION_REQUEST_CODE);
            }
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: called.");
        mLocationPermissionsGranted = false;

        switch(requestCode){
            case LOCATION_PERMISSION_REQUEST_CODE:{
                if(grantResults.length > 0){
                    for(int i = 0; i < grantResults.length; i++){
                        if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                            mLocationPermissionsGranted = false;
                            Log.d(TAG, "onRequestPermissionsResult: permission failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: permission granted");
                    mLocationPermissionsGranted = true;
                    //initialize our map
                    initMap();
                }
            }
        }
    }

}

另外,在清单文件中进行以下更改: -

<meta-data android:name="com.google.android.geo.API_KEY"
 android:value="YOUR_API_KEY"/>

以上是关于启动活动时出现Google Maps API密钥错误的主要内容,如果未能解决你的问题,请参考以下文章

Android Manifest 未向 Google Maps 提供 API 密钥

尝试使用 Google Maps API 旋转地图时出现问题

如何在现有的旧版Android项目中使用最新的API添加Google Map?

生成 Google 地图发布密钥

Google Maps API V3 中的 API 密钥是啥?

需要将新的Google Maps API KEY添加到我现有的Drupal7网站