谷歌地图显示空白屏幕,之前工作正常,但重新安装android studio后停止

时间:2018-10-21 13:26:55

标签: android google-maps

我正在尝试在一个非常简单的应用程序中显示Google地图。在这个项目中,我想以GPS位置显示用户的位置。这是清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hamzah.locationtracker">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!--
             The API key for Google Maps-based APIs is defined as a string 
resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to 
sign the APK.
             You need a different API key for each encryption key, including 
the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in 
src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我在@ string / google_maps_key中有一个有效的密钥,因为我之前说它可以正常工作。 主要活动:

package com.hamzah.locationtracker;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

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.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
    final static int PERMISSION_ALL = 1;
    final static String[] PERMISSIONS = {android.Manifest.permission.ACCESS_COARSE_LOCATION,

        Manifest.permission.ACCESS_FINE_LOCATION};
private GoogleMap mMap;
MarkerOptions mo;
Marker marker;
LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    mo = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location");
    if (Build.VERSION.SDK_INT >= 23 && !isPermissionGranted()) {
        requestPermissions(PERMISSIONS, PERMISSION_ALL);
    } else requestLocation();
    if (!isLocationEnabled())
        showAlert(1);
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    marker = mMap.addMarker(mo);
    /**
     * LatLng sydney =  new LatLng(-34,151);
     * mMap.addMarker(newMarkerOptions().positions)
     */
}


@Override
public void onLocationChanged(Location location) {
    LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
    marker.setPosition(myCoordinates);
    int zoom = 15;
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, zoom));
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

private void requestLocation() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_HIGH);
    String provider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    locationManager.requestLocationUpdates(provider, 1000, 10, this);
}

private boolean isLocationEnabled() {
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean isPermissionGranted(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("myLog", "Permission is Granted");
            return true;
        }else {
            Log.v("myLog", "Permission not Granted");
            return false;
        }
    }
    return false;
}
    private void showAlert(final int status) {
    String message, title, btnText;
    if (status == 1) {
        message = "Your Location Setting is set to 'Off'\nPlease Enable Location to " +
                "use this app";
        title = "Enable Location";
        btnText = "Location Settings";
    } else {
        message = "Please Allow this app to access location!";
        title =  "Permission Access";
        btnText = "Grant";
    }
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setCancelable(false);
    dialog.setTitle(title)
            .setMessage(message)
            .setPositiveButton(btnText, new DialogInterface.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.M)
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    if (status == 1) {
                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(myIntent);
                    } else
                        requestPermissions(PERMISSIONS, PERMISSION_ALL);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    finish();
                }
            });
    dialog.show();
    }
}

未更改布局文件

这是gradle文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.hamzah.locationtracker"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    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'
}

当我执行该应用程序时,我只得到一个空白屏幕和左下角的Google徽标屏幕。我正在使用仿真器Google XL API级别25,以及物理设备Samsung S4 API级别22。

2 个答案:

答案 0 :(得分:0)

您可能有一个新密钥,因此您需要在API控制台中对其进行更新

转到此处:https://console.cloud.google.com/google/maps-apis/api-list

  • 然后登录并选择您的项目。
  • 然后单击Maps SDK for Android
  • 然后选择“ Credentials”寄存器,然后选择API-key

您将看到一个这样的表:

enter image description here

,这是您输入SHA1哈希的地方。请注意,如果您使用其他签名密钥,例如开发和生产,您可以为同一个程序包注册多个散列,

答案 1 :(得分:0)

只需从控制台重新生成Maps Api密钥,然后在您的项目中将旧的替换为新的