为什么getLastLocation()方法在第一次启动应用程序时没有检索位置?

时间:2016-07-13 17:44:25

标签: android location android-location locationmanager location-services

我正在开发Android应用,我想在应用启动后立即检索用户的当前位置。

我正在使用此代码:

@Override
    public void onConnected(@Nullable Bundle bundle) {
        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) {
            currentLatDouble = mLastLocation.getLatitude();
            currentLngDouble = mLastLocation.getLongitude();
        }
    }

我正在使用Snackbar,当未检测到该位置时会弹出import pandas as pd df = pd.DataFrame({'serial_number': range(1, 12), 'item_name': list(map(lambda x: 'foo' + str(x), [1, 2, 3, 4, 5, 6, 7, 7, 8, 8, 9])), 'status': ['done', 'done', 'not_done', 'not_done', 'on_hold', 'not_done', 'done', 'done', 'not_done', 'on_hold', 'on_hold'], 'date': ['2015-01-01', '2016-01-01', '2015-02-12', '2016-01-12', '2015-03-13', '2016-02-13', '2016-03-14', '2016-02-15', '2016-03-16', '2016-04-17', '2016-04-18']}) df['date'] = pd.to_datetime(df['date']) 并且有一个"重试"按钮。按下那个"重试"按钮,再次执行上面的代码,这次检索位置。

我想要的是,我想在应用程序启动后立即检索该位置。

请告诉我。

1 个答案:

答案 0 :(得分:0)

如果还没有上一个已知位置,LocationServices.FusedLocationApi.getLastLocation方法可能会返回null

最好的用途是请求位置更新并处理onLocationChanged回调中的响应,如下所示:

@Override
public void onConnected(Bundle connectionHint) {
    ...
    if (mRequestingLocationUpdates) {
        startLocationUpdates();
    }
}

protected void startLocationUpdates() {
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}

LocationListener将处理收到的位置

public class MainActivity extends ActionBarActivity implements LocationListener {
...
@Override
public void onLocationChanged(Location location) {
    mCurrentLocation = location;
}

请务必查看documentations。这个answer也可以帮到你。