【发布时间】: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