如果网络不可用或发生任何其他 I/O 问题,它会抛出 IOException。它需要互联网连接才能使用地理编码器。
public class MainActivity extends Activity {
double LATITUDE = 37.42233;
double LONGITUDE = -122.083;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
TextView myAddress = (TextView)findViewById(R.id.myaddress);
myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
e.printStackTrace();
myAddress.setText("Cannot get Address!");//and tell me what is
}
}
}
有人知道吗?
我已经设法用 Emulator 2.1 api 8 做到了,但是反向地理编码总是给出一个空的结果。任何人都可以确认我的代码?
原木猫
06-03 10:59:24.689: W/System.err(4129):java.io.IOException: Service not Available
:at android.location.Geocoder.getFromLocation(Geocoder.java:136)
:at com.example.gprsonandoff.MainActivity.city(MainActivity.java:74)
:at com.example.gprsonandoff.MainActivity.onCreate(MainActivity.java:44)
:android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
:at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)