【发布时间】:2013-01-02 09:27:21
【问题描述】:
我正在开发基于位置的小型 android 应用程序,我需要用户当前的位置。一旦位置发生一些变化,我也会更新用户当前位置。我的代码如下所示:
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String svcName = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(svcName);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
//Location l = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
Location l = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(l);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
}
private void updateWithNewLocation(Location location)
{
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String latLongString = "No location found";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
}
myLocationText.setText("Your Current Position is:\n" +
latLongString);
}
我的问题是,当我使用提供商作为网络时,它工作正常。但是当它选择 gps 作为提供者时,它会给出空值。我第一次知道它给了我空值。我也使用了 onLocationChanged 方法,但它仍然没有给我正确的输出。 当我打开我的应用程序时,它会显示输出空值,它还会启动 gps 来搜索我的位置。我等待一段时间来获取更新的位置,但它没有给我有效的输出。 我的代码有什么问题吗。 我正在使用安卓设备。
需要帮助...谢谢...
【问题讨论】:
标签: android geolocation gps location