Android AsyncTask 卡住 UI

标签 android user-interface android-asynctask freeze

我正在尝试从服务器获取数据。尽管我在 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/

相关文章:

c++ - 编写应用程序核心和 gui 分离的最佳实践?

java - 无法从 AsyncTask 更新 UI

java - onResume() 更新 TextView

python-3.x - 在Python3/tkinter中如何拦截用户单击顶级窗口上的关闭按钮

Android 动态 View /布局 - 服务器端 View /布局生成

java - 避免应用程序在捕获异常时崩溃

java - 如何将 HttpUrlConnection 的逻辑拆分为多个方法?

c# - 在 Visual Studio 2010 控制台应用程序中以管理员身份运行 BAT 文件

android - 为警报调用 Intent 时出现 IllegalStateException

php - 如何在android java中获取关联数组元素?