android studio-asynctask get()冻结用户界面

a2mppw5e  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(321)

当我使用 Asynctask ,执行它并尝试使用 get()onCreate 方法它冻结了我的整个ui。
我的任务类:

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);

如何修复这个问题并在下载html后记录文本而不冻结ui?
谢谢

ylamdve6

ylamdve61#

如前所述 AsyncTask 已弃用。你最好使用android截击之类的工具
内部版本.gradle:

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

androidmanifest.xml:

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

在你的片段或类或任何东西里面:

// 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);

相关问题