【问题标题】:Trying to multi thread a network task in android尝试在android中对网络任务进行多线程处理
【发布时间】:2014-05-11 13:26:01
【问题描述】:

我在使用 Android 中的另一个线程检查 Web 服务器的可用性时遇到问题。

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

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 行被注释。我已经尝试在谷歌上搜索具体问题,但结果好坏参半。

任何帮助将不胜感激。

非常感谢

【问题讨论】:

    标签: java android multithreading networking


    【解决方案1】:

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

    你可以使用

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

    pingResult.setText("WRONG"); 也一样

    但最好使用 AsyncTask,因为它会更容易。在这种情况下,您可以在doInBackground 返回结果(即字符串)中进行后台计算,并在onPostExecute 中更新ui

    【讨论】:

      猜你喜欢
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多