求教关于GPS代码的一些问题
public class GeoLocDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
LocationManager locationManager;
locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
}
private final LocationListener locationListener = new LocationListener(){
public void onLocationChanged(Location location){
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras){
}
};
private void updateWithNewLocation(Location location){
TextView MyLocationText = (TextView)findViewById(R.id.MylocationText);
String latLongString;
String addressString = null;
if(location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "纬度:"+lat+",经度:"+lng;
Geocoder gc = new Geocoder(this, Locale.getDefault());
try{
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if(addresses.size()>0){
Address address =addresses.get(0);
for(int i=0; i< address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
addressString = sb.toString();
}else
addressString = "地址没有找到.";
}catch(IOException e){ }
}else{
latLongString = "未发现位置";
}
MyLocationText.setText("位置:\n" +latLongString + "\n\n地址:\n"+addressString);
}
}
编译通过了,但是运行的时候总是显示 地址:null
想问一下是什么原因呢,是不是因为开始的时候定义了String addressString = null; else中的addressString = "地址没有找到.";不可以这样用么?
菜鸟,求教。
提前谢谢大家O(∩_∩)O~