通过处理器/ AsyncTask的或类似的运行网络任务 [英] Using a handler / AsyncTask or similar to run a networking task

查看:120
本文介绍了通过处理器/ AsyncTask的或类似的运行网络任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,该错误发生,因为我尝试把一个网络调用的主线程上,所以我需要使用一个处理器或AsyncTask的

i am aware that the error is occurring because im trying to put a network call on the main thread so i need to use a handler or asynctask

但我不似乎能够得到它的权利。

however i dont seem to be able to get it right

这是code我尝试去上班。

this is the code im trying to get to work

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

和我想将它命名这个按钮被点击时

and i want to call it when this button is clicked

public void onClick(View v) {

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

有没有人能告诉我什么我应该换第一位的,以及如何将其从的onClick

is anyone able to show me what i should wrap the first bit in and how to call it from the 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。

Do all heavy-lifting in doInBackground() and you can update the UI in the other 3 methods.

这里 在文档AsyncTask的

Here is the documentation on AsyncTask

这篇关于通过处理器/ AsyncTask的或类似的运行网络任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆