【发布时间】:2025-09-21 02:55:02
【问题描述】:
我是 Android 新手,我正在尝试开发一个显示用户当前位置的 Android 应用程序。我正在使用 Genymotion。现在我正在使用
mLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
获取设备的最后位置。问题是我想获得当前位置,但有了这个我得到mlocation 不为空,这很好。但在地图中,它始终显示设备的最后位置,而不是当前位置。
代码 sn-p
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "inside onconnected Location services connected");
Location mLocation=null;
mLocationRequest= new LocationRequest();
mLocationRequest.setInterval(10 * 1000) ;
mLocationRequest.setFastestInterval(1 * 1000);mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
}
mLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
if(mLocation==null)
{
Log.d("***Inside mlocation***", "***mlocation is null here");
}
if (mLocation != null) {
onLocationChanged(mLocation);
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleClient, mLocationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude,currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Im here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
在onstart() 中,我调用了googleapi.connect(),并适当地使用了setUpMapIfNeeded()。
请告诉我这段代码有什么问题。我正在尝试这个 3 天。
【问题讨论】:
-
在您的代码中没有提及 gps 开/关。你应该在应用程序前台打开gps。
-
嗨,杰伊,我的模拟器中的 gps 已打开,但我从你的陈述中了解到,我需要检查 gps 的可用性,对吗??但我认为它也没有任何区别。
-
检查我的答案@Navi