我有一张要从单独的线程更新的地图。当我尝试从扩展 asynctask 的类中更新 UI 时,我遇到了一些问题。当我将代码移动到主线程中的处理程序时,我得到了NetworkOnMainThreadException
. 下面是我的异步任务。有没有办法修改它以使其工作?
@Override
protected Integer doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://83.xx.xx:8080/android/service.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "getusers"));
nameValuePairs.add(new BasicNameValuePair("interval", Integer.toString(interval)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String jsonString = EntityUtils.toString(response.getEntity());
Gson gson = new GsonBuilder().create();
Type listType = new TypeToken<ArrayList<User>>() {}.getType();
ArrayList<User> userList = gson.fromJson(jsonString, listType);
((GoogleMapsActivity) activity).removeOverlayItems();
for(User user : userList ){
((GoogleMapsActivity) activity).addOverlayItem(Double.parseDouble(user.last_lat), Double.parseDouble(user.last_lng), user.bluetooth_name, "test desc");
}
return 1;
} catch (Exception e) {
e.printStackTrace();
}
return null;