java - 使用处理程序/AsyncTask 或类似的程序来运行网络任务

标签 java android android-asynctask

我知道发生错误是因为我试图在主线程上进行网络调用,所以我需要使用处理程序或异步任务

但是我似乎无法做到这一点

这是我试图开始工作的代码

 try {
                // Create a URL for the desired page
                URL url = new URL("http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt");


                // Read all the text returned by the server
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                String str;
                while ((str = in.readLine()) != null) {
                    // str is one line of text; readLine() strips the newline character(s)

                    eventText.setText(str);
                    eventText.setText(in.readLine());
                }
                in.close();
            } catch (MalformedURLException e) {
                Toast.makeText(getBaseContext(), "MalformedURLException", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                Toast.makeText(getBaseContext(), "IOException", Toast.LENGTH_LONG).show();
            }

我想在单击此按钮时调用它

public void onClick(View v) {

if (v.getId() == R.id.update) {
}
}

有谁能够告诉我应该将第一个部分包含在内以及如何从 onClick 中调用它

最佳答案

类似

public class TalkToServer extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

    }

    @Override
    protected String doInBackground(String... params) {
    //do your work here
        return something;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
           // do something with data here-display it or send to mainactivity
}

doInBackground() 中完成所有繁重的工作,您可以在其他 3 种方法中更新 UI。

<强> Here 是AsyncTask的文档

关于java - 使用处理程序/AsyncTask 或类似的程序来运行网络任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13882095/

相关文章:

java - 不兼容类型 : String cannot be converted to File

java - ASyncTask 导致 getDatabaseLocked

android - 为什么我们应该使用 aysntask 或 service 而不是新线程

java - JSF 2 找不到我的 xhml 文件

java - 关闭 Android 应用程序及其在 Home press 上运行的功能

android - 了解 RecyclerView setHasFixedSize

java - 为每个作业单独的专用异步任务类或接受大量参数的统一通用类

java - Jetty HttpClient 是如何使用线程的?

Java代码读取网站内容

android - onSuccessListener中文件上传成功时如何返回 bool 值?