我试图通过GPS从安卓手机获得纬度和经度信息,当我在户外或直接在天空下时,我能够立即获得这些值,但当我在室内或房间内时,它需要一分钟多的时间才能获得这些值。当我在房间内使用我的应用程序时,谁能帮助我快速获得这个值?
我使用以下代码来获取值:
LocationManager locManager;
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f,
locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
和
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
EditText myLocationText = (EditText)findViewById(R.id.editText1);
EditText myLocationText1 = (EditText)findViewById(R.id.editText2);
String latString = "";
String LongString = "";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latString = "" + lat;
LongString ="" + lng;
} else {
latString = "No location found";
LongString = "No location found";
}
myLocationText.setText(""+ latString);
myLocationText1.setText(""+ LongString);
}
除了使用LocationManager
之外,还有其他方法可以获得GPS值吗??
你可以得到最后一个已知的位置,而且相当快:
/**
* Gets the last known location.
*
* @param locationManager the location manager
* @return the last known location
*/
public static Location getLastKnownLocation(LocationManager locationManager)
{
Location bestResult = null;
float bestAccuracy = 10000;
long bestTime = 0;
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Log.d("LOCATION", "Provider: " + provider);
Location location = locationManager.getLastKnownLocation(provider);
Log.d("LOCATION", "Location found? "+ (location==null?"NO":"YES"));
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
Log.d("LOCATION", "Acc: "+ String.valueOf(accuracy) + " -- Time: " + String.valueOf(time));
if ((time > minTime && accuracy < bestAccuracy)) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
}
else if (time < minTime &&
bestAccuracy == Float.MAX_VALUE && time > bestTime){
bestResult = location;
bestTime = time;
}
}
}
Log.d("LOCATION", "BEST FOUND? "+ (bestResult==null?"NO":"YES"));
return bestResult;
}
您可以在LocationManager中使用以下方法获得设备的最后已知位置,这是最后在系统范围内找到的位置。
这个方法是关键:
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
查看详细信息获取用户位置
如果您在室内,您最好使用LocationManager.NETWORK_PROVIDER
,因为您不太可能在室内获得信号。您也可以使用getLastKnownLocation()
,但这可能不存在或过时。
如果你想在一个房间里获得位置,gps提供商是缓慢的。你可以试着修改:
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f,
locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
由:locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000L,500.0f,
locationListener);
您将在'public void onLocationChanged(location location)'方法中接收location
我使用网络提供商来获取坐标,它总是更快的房子里的客厅。但当我在地下室区域尝试同样的操作时,它根本无法获取坐标,尽管我等了差不多几分钟。
注意:我可以从地下室打电话,我也可以浏览…