没有手机服务的设备上的 FusedLocationAPI 问题

Problems with FusedLocationAPI on device without Cell Service

我正在使用 SIM 卡但没有手机服务的设备上测试 Android 应用程序。我通过清单打开了 "coarse" 和 "fine" 位置 API:

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.LOCATION_HARDWARE" />

这是我通过 activity 的继承方法初始化 GoogleApiClient 的代码:

import com.google.android.gms.common.api.GoogleApiClient.*;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;

....

protected GoogleApiClient googleApiClient;
protected boolean locationServicesIsAvailable = false;
protected Location lastKnownLocation;

protected synchronized void buildGoogleApiClient() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

protected Location getLastKnownLocation() {
    if(googleApiClient == null) {
        buildGoogleApiClient();
        return null;
    } else
        return LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}

@Override
public void onConnected(Bundle bundle) {
    locationServicesIsAvailable = true;
    // @TODO signal the rest of the app that current location is now available
    lastKnownLocation = getLastKnownLocation();
    API.log("Geo location reported! => " + lastKnownLocation.toString());
}

问题似乎是 onConnected() 回调没有触发,即使在设备上启用了 GPS。我做错了什么?

我想我会 post 一个解决这个问题的答案 - 谢谢 Daniel 和 CaseyB!问题是我正在连接 API 客户端,但没有调用 connect() 方法。在 buildGoogleApiClient() 方法中添加这一行,就在 googleApiClient 上的 build() 链调用之后是修复:

googleApiClient.connect();

您还可以在 build() 之后链接 connect() 调用。