Ale*_*der 1 user-interface android freeze android-asynctask
我正试图从服务器获取数据.尽管事实上我在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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可能在滥用AsyncTask.你应该像这样在外部调用它:
new YourAsyncTask().execute();
Run Code Online (Sandbox Code Playgroud)
如果你这样调用:"new YourAsyncTask().get()"它将阻止UI线程.
请参阅此处的一些用法参考:http: //developer.android.com/reference/android/os/AsyncTask.html