Google 地图 API Android 设置最后位置错误

Google Maps API Android setting up last location errors

所以我尝试按照此处所示的最后一个位置的教程进行操作 http://developer.android.com/training/location/retrieve-current.html

我没有将标记添加到片段中,这表明标记正在正确更新。我已经在我的主要项目上试过了,但没有用。因此,我尝试在一个全新的项目中严格按照教程进行操作,以查看是否可以解决该问题。

我想知道这是否是我正在使用的模拟器的问题(肯定是使用 google API 6.0 版),因为我无法 运行示例项目也正确

以下是我使用过的文件和生成的错误日志 MapTesting.java

package dominic.maptesting;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
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.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

 private GoogleMap mMap;
 private GoogleApiClient mGoogleApiClient;
 private Location mLastLocation;

 @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);

  if (mGoogleApiClient == null) {
   mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build();

  }

 }

 @Override
 public void onConnected(Bundle connectionHint) {
  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;
  }
  mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
   mGoogleApiClient);
  if (mLastLocation != null) {
   LatLng test = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
   mMap.addMarker(new MarkerOptions().position(test).title("Marker Test"));
   mMap.moveCamera(CameraUpdateFactory.newLatLng(test));

  } else {}

 }

 @Override
 public void onConnectionSuspended(int i) {

 }

 protected void onStart() {
  mGoogleApiClient.connect();
  super.onStart();
 }

 protected void onStop() {
  mGoogleApiClient.disconnect();
  super.onStop();
 }


 @Override
 public void onMapReady(GoogleMap googleMap) {
  mMap = googleMap;

 }

 @Override
 public void onConnectionFailed(ConnectionResult connectionResult) {

 }
}

Activity_Map.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dominic.maptesting.MapsActivity" />

AppManifest

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

<!--
     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" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_GPS"/>


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    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>

01-26 17:21:51.228 3427-3427/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-26 17:21:51.228 3427-3427/? E/android.os.Debug: failed to load memtrack module: -2
01-26 17:21:51.255 1299-1339/? E/InputDispatcher: channel 'b6f8f72 dominic.maptesting/dominic.maptesting.MapsActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-26 17:21:51.991 959-959/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
01-26 17:21:53.175 3440-3440/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-26 17:21:53.175 3440-3440/? E/android.os.Debug: failed to load memtrack module: -2
01-26 17:21:53.244 3436-3436/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-26 17:21:53.244 3436-3436/? E/android.os.Debug: failed to load memtrack module: -2
01-26 17:21:53.725 1598-1872/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4093960
01-26 17:21:54.666 948-2693/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property

非常感谢任何建议或帮助。我非常坚持这个并且是 android

的新手

如果您仔细查看以下代码块导致的问题。

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;
  }

在 Android 6.0 上,此块将 return 为真,函数将退出而不进一步执行 code.The 原因是您的目标是 android 6.0 版本,而您不是处理运行时权限。请阅读本文以了解 Android 运行时权限。

http://developer.android.com/training/permissions/requesting.html https://github.com/googlesamples/android-RuntimePermissions

仍然在使用运行时权限后,您可能不会在地图上看到标记,因为 LocationServices.FusedLocationApi.getLastLocation 可能只是 return null,因此您也必须处理该逻辑。