我試圖從服務器獲取數據。儘管我在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