以下是使用线程和处理程序的完整示例代码,以在不阻塞用户界面的情况下获取地理编码器答案。
地理编码器调用过程可以位于 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);
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());
并且在你的用户界面中显示结果的处理程序:
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;
}
myLabel.setText(result);
}
}
别忘了在你的Manifest.xml
中加入以下权限。
<uses-permission android:name="android.permission.INTERNET" />