我正在使用Google Service API,LocationServices.FusedLocationApi来查找用户当前然后更新的位置。我已经在模拟器和实际设备上进行了测试,我发现如果我关闭GPS LocationServices.FusedLocationApi.getLastLocation()总是返回null,但是如果我打开GPS,我会得到一个有效值。这是我正在使用的代码:
private GoogleApiClient mGoogleApiClient;
private Location mLastKnownLocation;
mLastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastKnownLocation != null) {
Log.i(TAG, String.valueOf(mLastKnownLocation.getLatitude()));
Log.i(TAG, String.valueOf(mLastKnownLocation.getLongitude()));
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, createLocationRequest(), this);
我在这里遗漏了什么吗? 提前谢谢。
答案 0 :(得分:2)
我认为您应首先使用以下方法检查您的设备是否具有GPS:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
然后使用LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)
。
有关详细信息和代码,请参阅here。