【问题标题】:Android Studio - Asynctask get() freezes UIAndroid Studio - Asynctask get() 冻结 UI
【发布时间】:2021-03-10 20:55:54
【问题描述】:

在 Android Studio 中,当我使用 Asynctask 时,执行它并尝试在 onCreate 方法中使用 get(),它会冻结我的整个 UI。

我的 Asynctask 类:

public class HTMLDownload extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try {

            url = new URL(urls[0]);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(inputStream);

            int data = reader.read();

            while (data != -1) {

                char current = (char) data;

                result += current;

                data = reader.read();

            }
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return "Failed";
        }
    }

我的onCreate方法代码:

    HTMLDownload task = new HTMLDownload();

    try {
        String result = task.execute("https://www.telltalesonline.com/26925/popular-celebs/").get();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
         e.printStackTrace();
    }

     Log.i("Result", result);

如何在不冻结 UI 的情况下解决此问题并在下载 HTML 后记录文本?

谢谢

【问题讨论】:

  • 不要使用已弃用的 asynctask。使用任何其他线程机制。

标签: java android android-asynctask


【解决方案1】:

如前所述,AsyncTask 已弃用。你最好使用Android Volley

build.gradle:

dependencies {
    // ...
    implementation 'com.android.volley:volley:1.1.1'
}

AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

在您的 Fragment 或类或其他任何内容中:

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = "https://www.telltalesonline.com/26925/popular-celebs/";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // TODO handle the response
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO handle error
            }
        }
);

// Add the request to the RequestQueue.
queue.add(stringRequest);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多