首先,抱歉我的英语不好,我是葡萄牙语,我肯定会犯一些英语语法错误。
好吧,我正在尝试使用AsyncTask类从googleMap加载地图,但是它显示了以下错误消息:
06-25 18:47:03.062: E/AndroidRuntime(8021): FATAL EXCEPTION: AsyncTask #1
06-25 18:47:03.062: E/AndroidRuntime(8021): java.lang.RuntimeException: An error occured while executing doInBackground()
06-25 18:47:03.062: E/AndroidRuntime(8021): at java.lang.Thread.run(Thread.java:856)
06-25 18:47:03.062: E/AndroidRuntime(8021): Caused by: java.lang.IllegalStateException: Not on the main thread
我的主类调用AsyncTask类
public class ExemploGPSSimples extends FragmentActivity {
protected GoogleMap map;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.exmeplo_gps);
}
@Override
protected void onResume() {
super.onResume();
configuraGPS();
}
private void configuraGPS() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_gps);
map = mapFragment.getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//LatLng local=pegaPosicaoAtual();
Localizador localizador = new Localizador(this);
String endereco="Av. João Pessoa, 1091, Porto Alegre, RS";
LatLng local = localizador.getEndereco(endereco);
SincronizaMapa sincronizaMapa = new SincronizaMapa(this,local,map);
sincronizaMapa.execute();
adicionaMarcador(map,local);
map.setMyLocationEnabled(true);
}
private void adicionaMarcador(GoogleMap map2, LatLng local) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(local).title("Luiz").snippet("Casa");
Marker marker = map2.addMarker(markerOptions);
}
}
最后是AsyncTask类
public class SincronizaMapa extends AsyncTask<Void, Void, Void> {
private final Activity activity;
private final LatLng local;
private final GoogleMap map;
private ProgressDialog progressDialog;
public SincronizaMapa(Activity activity, LatLng local,
GoogleMap map) {
this.activity = activity;
this.local = local;
this.map = map;
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(activity, "Sincronizando mapa", "Aguarde...",true,true);
}
@Override
protected Void doInBackground(Void... params) {
CameraPosition position = new CameraPosition.Builder()
.target(local)
.bearing(0)
.tilt(0)
.zoom(17)
.build();
CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
map.animateCamera(update);
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
谢谢大家的帮助。
答案 0 :(得分:8)
map.animate修改UI组件(地图),因此必须在UI线程上完成。 您可以将需要在UI线程上的代码移动到onPostExecute
答案 1 :(得分:5)
问题是您正在尝试从UI线程以外的线程更新UI。 asyncTasks允许你在保持UI线程空闲的同时进行后台工作(doInBackgroud),然后根据(onPostExecute)更新UI。
你应该将doInBackground的主体放在onPostExecute的主体中 - 在UI线程上运行的方法。