2015-11-22 38 views
-1

我一直在检索用户在我的应用程序的位置问题。我使用的是官方文档建议的代码,也就是我用的Android - 用户位置

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
       mGoogleApiClient); 

得到最后一个已知的位置。 由于某些原因,getLastLocation在每次执行时都返回null。我在我的清单中添加了ACCESS_FINE_LOCATION权限。 其他人似乎也有同样的问题,但我无法得到明确的解决方案。 我看不出为什么这不起作用。 难道是因为我正在使用模拟器来测试应用程序吗? 如果不是有其他选择吗?

回答

1

我前几天实施了Google位置API,并且工作正常。 既然你还没有显示任何代码,我会告诉你我是如何设置我的应用程序使用API​​,希望这会帮助你。

我采用了android studio.In我项目的gradle这个我已经添加了以下的依赖:(请务必在更新此版本号每次谷歌Play服务更新) classpath 'com.google.gms:google-services:1.5.0-beta2'

在我模块的gradle这个我已经添加以下依赖: compile 'com.google.android.gms:play-services-location:8.4.0'(请务必在更新此版本号每次谷歌Play服务更新)

的manifest.xml

<manifest 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
... 
<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme" > 
    <meta-data 
     android:name="com.google.android.gms.version" 
     android:value="@integer/google_play_services_version" /> 
    <meta-data 
     android:name="com.google.android.geo.API_KEY" 
     android:value="@string/android_api_key"/> 
    <uses-feature 
     android:glEsVersion="0x00020000" 
     android:required="true"/> 
    <activity 
... 

的strings.xml 你需要从google developers console

<string name="android_api_key">putyourapikeyhere</string>

活动或片段

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{ 
private GoogleApiClient mGoogleApiClient; 
private LocationRequest mLocationRequest; 
一个Android API密钥(参见清单第2元数据标记)

在活动'如果你使用它的片段建立它在它的onCreate

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

mGoogleApiClient = new GoogleApiClient.Builder(getContext()) 
      .addApi(LocationServices.API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .build(); 
mGoogleApiClient.connect(); 

的区别在于GoogleApiClient.Builder的输入参数s中的onCreate建立你GoogleApiClient。

接下来,您必须实现回调

@Override 
public void onConnected(Bundle bundle) { 
    mLocationRequest = LocationRequest.create(); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    lat = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient).getLatitude(); 
    lng = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient).getLongitude(); 
} 
@Override 
    public void onConnectionSuspended(int i) { 
} 
@Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
}