我正在尝试从服务器获取数据。尽管我在 doinbackground 方法中进行了所有连接和提取数据,但 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();
}
}
}
最佳答案
您可能误用了 AsyncTask。你应该像这样在外部调用它:
new YourAsyncTask().execute();
如果您这样调用:“new YourAsyncTask().get()”,它将阻塞 UI 线程。
在这里查看一些用法引用: http://developer.android.com/reference/android/os/AsyncTask.html
关于Android AsyncTask 卡住 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23817356/