试图在android中多线程一个网络任务

时间:2014-05-11 13:26:01

标签: java android multithreading networking

我在使用Android中的其他线程检查网络服务器的可用性时遇到了问题。

我开始一个新线程以避免:

NetworkOnMainThreadException

这是日志猫:

E/AndroidRuntime(17753): FATAL EXCEPTION: Thread-2370
E/AndroidRuntime(17753): Process: com.example.c3po, PID: 17753
E/AndroidRuntime(17753): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
E/AndroidRuntime(17753): at com.example.c3po.MainActivity$1SecondThread.run(MainActivity.java:72)

第二个帖子中使用的代码

class SecondThread extends Thread {

        public void run() {

            TextView pingResult = (TextView) findViewById(R.id.checkStatus); // to display result

            EditText userText = (EditText) findViewById(R.id.userData); // take in user url
            String result = userText.getText().toString();

            try {

                InetAddress address = InetAddress.getByName(result); // user input is result (a URL)
                boolean b = address.isReachable(3000); 
                String str = String.valueOf(b); // turning the value of the boolean into string
                pingResult.setText(str); // value displays as true or false - LINE 72

            }
            catch (UnknownHostException e) {pingResult.setText("WRONG");} // will fill with helpful message later
            catch (IOException e) {pingResult.setText("WRONG");}


        }

触发线程的按钮:

    Button sendPing = (Button) findViewById(R.id.pingButton);
    sendPing.setOnClickListener(new OnClickListener() {

        public void onClick (View activity_main) {

            SecondThread thread = new SecondThread();
            thread.start();

        }

    });

第72行被评论。我试过谷歌搜索特定的问题,但结果好坏参半。

任何帮助都将不胜感激。

非常感谢

1 个答案:

答案 0 :(得分:0)

您正在从后台线程更新ui。你不能这样做。 Ui需要在ui线程上更新。使用AsyncTask

您可以使用

    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pingResult.setText(str); 
                        }
                 });

同样适用于pingResult.setText("WRONG");

但最好使用AsyncTask,因为它会更容易。您可以在doInBackground返回结果中进行背景计算,即本例中的字符串,并在onPostExecute中更新ui