我试图从服务器获取数据。尽管我在doinbackground方法中完成所有的连接和提取数据,但UI以某种方式冻结。如果有人能帮助我,我将非常感激,因为我检查了有关此主题的所有问题,但未找到解决方案。Android AsyncTask冻结UI
public class GetMessagesActivity extends AsyncTask<String, Void, String> {
private Context context;
private ProgressDialog progressDialog;
public GetMessagesActivity(Context context) {
this.context = context;
this.progressDialog = new ProgressDialog(context);
this.progressDialog.setCancelable(false);
this.progressDialog.setMessage("Updating...");
this.progressDialog.show();
}
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... arg0) {
try {
String pid = "1";
String link = "somelink";
String data = URLEncoder.encode("pid", "UTF-8") + "="
+ URLEncoder.encode(pid, "UTF-8");
// data += "&" + URLEncoder.encode("password", "UTF-8")
// + "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
}
}
}
你如何执行任务您还没有显示。我会采取一个刺,猜测你正在使用'get()'来阻塞调用线程。 – ashishduh
你说得对。我删除了get()并使用了execute(),它完美地工作。非常感谢 – Alexander