Android - 用户的位置

时间:2015-11-22 14:05:25

标签: android gps location

我在检索用户在应用程序中的位置时遇到了问题。我使用了官方文档中建议的代码,也就是我使用的

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);

获取最后的已知位置。 出于某种原因,getLastLocation在每次执行时都返回null。我确实在清单中添加了ACCESS_FINE_LOCATION权限。 其他人似乎有同样的问题,但我无法得到一个明确的解决方案。 我认为没有理由不这样做。 可能是因为我使用模拟器来测试应用程序? 如果没有,有没有替代方案?

1 个答案:

答案 0 :(得分:1)

我几天前已经实施了Google Location api,并且工作正常。 由于您没有显示任何代码,我会告诉您如何设置我的应用程序以使用api,希望这对您有帮助。

我正在使用android studio。在我的项目的gradle 中,我添加了以下依赖项:     classpath 'com.google.gms:google-services:1.5.0-beta2'(每次更新Google Play服务时,请务必更新此版本号。)

在我的模块的gradle 中,我添加了以下依赖项:     compile 'com.google.android.gms:play-services-location:8.4.0'(每次更新Google 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

的android api密钥(请参阅清单中的第二个元数据标记)

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

活动或片段

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

在活动的onCreate中构建您的GoogleApiClient:

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

如果您在片段中使用它,请在其中创建onCreate:

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

区别在于GoogleApiClient.Builder的输入参数。

接下来,你必须实现回调

@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) {
}
相关问题