[英]android- How to update the location without opening the maps/navigation app
我想获得准确和准确的当前位置。 为此,我使用了位置管理器requestLocationUpdates()
方法,但是调用onLocationChanged()
方法将花费很多时间。 因此,我为此设置了计时器为20秒。 我的意思是即使20秒后也不会调用onLocationChanged()
方法,然后我决定采用最后一个已知位置。 在这里,我正面临这个问题。 getLastKnownLocation()
返回null。
但是我想要位置。 在这里,我找到了一个解决方案。 这是因为测试设备没有与gps提供商最近的位置更新。 因此,我们需要手动打开“地图/导航”应用,然后它将返回位置。 我们需要做些什么来获取位置,而不是打开“地图”应用。 我认为我们应该做与地图应用相同的位置更新。 我们如何像这样实现而不打开它。
//使用requestLocationUpdates获取当前位置
public void getLocation() {
locationManager.requestLocationUpdates(strProvider, 0, 0,
CurrentlocationListener);
}
LocationListener CurrentlocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
locationManager.removeUpdates(this);
double lat = location.getLatitude();
double lng = location.getLongitude();
String strCurrentLatitude = String.valueOf(lat);
String strCurrentLongitude = String.valueOf(lng);
System.out
.println("Current Latitude and Longitude(onLocation Changed): "
+ strCurrentLatitude
+ ","
+ strCurrentLongitude);
}
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
//使用lastknownlocation获取当前位置。
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(location_context);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
strProvider = locationManager.getBestProvider(crit, true);
Location location = locationManager
.getLastKnownLocation(strProvider);
System.out.println("location(geoPoint1): " + location);
String strCurrentLatitude = "0", strCurrentLongitude = "0";
if (location != null) {
strCurrentLatitude = String.valueOf(location
.getLatitude());
strCurrentLongitude = String.valueOf(location
.getLongitude());
}
您在OnLocationChanged()
中所做的任何操作都是正确的。 现在,用它替换LocationManager的代码。 会的
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 1000, 0, this);
}
谢谢。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.