我有一对坐标,我正在使用Geocoder.getFromLocation来获取地址详细信息。但是这种方法是同步的,并且会冻结应用程序一段时间。我试图将它放在 AsyncTask 中,但我得到了一个java.lang.IllegalStateException: Not on the main thread
.
有没有办法异步调用这个方法?
这是检索地址的方法(在 MapUtil 类中):
public static Address getAddress(Context context, Marker marker) {
Geocoder geocoder = new Geocoder(context);
Address address = null;
try {
List<Address> addressList = geocoder.getFromLocation(marker.getPosition().latitude, marker.getPosition().longitude, 1);
if (addressList != null && addressList.size() > 0) {
address = addressList.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return address;
}
这是我在 MainActivity 的 AsyncTask:
new AsyncTask<Void, Void, Void>() {
Address address = null;
@Override
protected Void doInBackground(Void... params) {
address = MapUtil.getAddress(MainActivity.this, marker);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("Address = " + address);
}
}.execute();
这是完整的堆栈跟踪:
11-13 06:36:12.423: W/System.err(17247): java.lang.IllegalStateException: Not on the main thread
11-13 06:36:12.423: W/System.err(17247): at maps.aq.o.b(Unknown Source)
11-13 06:36:12.423: W/System.err(17247): at maps.ak.g.b(Unknown Source)
11-13 06:36:12.423: W/System.err(17247): at maps.af.bk.c(Unknown Source)
11-13 06:36:12.423: W/System.err(17247): at cpd.onTransact(SourceFile:80)
11-13 06:36:12.423: W/System.err(17247): at android.os.Binder.transact(Binder.java:347)
11-13 06:36:12.423: W/System.err(17247): at com.google.android.gms.maps.model.internal.d$a$a.getPosition(Unknown Source)
11-13 06:36:12.423: W/System.err(17247): at com.google.android.gms.maps.model.Marker.getPosition(Unknown Source)
11-13 06:36:12.423: W/System.err(17247): at com.example.util.MapUtil.getAddress(MapUtil.java:17)
11-13 06:36:12.423: W/System.err(17247): at com.example.MainActivity$3.doInBackground(MainActivity.java:102)
11-13 06:36:12.423: W/System.err(17247): at com.example.MainActivity$3.doInBackground(MainActivity.java:1)
11-13 06:36:12.423: W/System.err(17247): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-13 06:36:12.423: W/System.err(17247): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-13 06:36:12.423: W/System.err(17247): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-13 06:36:12.423: W/System.err(17247): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-13 06:36:12.423: W/System.err(17247): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-13 06:36:12.423: W/System.err(17247): at java.lang.Thread.run(Thread.java:841)