这是一个完整的示例代码,使用 Thread 和 Handler 在不阻塞 UI 的情况下获取 Geocoder 答案。
Geocoder 调用过程,可以位于一个 Helper 类中
public static void getAddressFromLocation(
final Location location, final Context context, final Handler handler) {
Thread thread = new Thread() {
@Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality();
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to Geocoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
以下是您的 UI Activity 中对此 Geocoder 过程的调用:
getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());
以及在您的 UI 中显示结果的处理程序:
private class GeocoderHandler extends Handler {
@Override
public void handleMessage(Message message) {
String result;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
result = bundle.getString("address");
break;
default:
result = null;
}
// replace by what you need to do
myLabel.setText(result);
}
}
不要忘记将以下权限放入您的Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />