没有Cell Service的设备上的FusedLocationAPI问题

时间:2015-07-24 14:53:45

标签: android android-location

我在拥有没有手机服务的SIM卡的设备上测试Android应用。我有两个"粗"并且"罚款"通过清单打开位置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" />

这是我通过继承的活动方法初始化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());
}

问题似乎是即使在设备上启用了GPS,onConnected()回拨也不会被触发。我做错了什么?

1 个答案:

答案 0 :(得分:0)

想我会发一个答案来关闭它 - 谢谢Daniel&amp; CaseyB!问题是我在连接API客户端但没有调用connect()方法。在buildGoogleApiClient()方法中添加此行,就在build()上的googleApiClient链调用之后就是修复:

googleApiClient.connect();

您还可以在connect()后的build()来电中进行链接。