java - android ping InetAddress 和 editText

标签 java android eclipse ping inetaddress

我想在EditText框中输入IP, 然后通过按钮 ping(可达或不可达)在 textView 中提供结果

public class MainActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
            EditText editText = (EditText) findViewById(R.id.editText1);
            TextView textView = (TextView) findViewById(R.id.textView);
             String input= editText.getText().toString();

               InetAddress ip;
                ip = InetAddress.getByName(input);
                boolean reach= ip.isReachable(5000);
                   textView.setText("real ?"+reach);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
    });
}   
}

每当我在真实手机中按下 ping 按钮时,它就会从应用程序中出来,为什么?

最佳答案

我猜你的net方法错了,试试这个代码,如果仍然这样 不可行请告诉我。

public class MainActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
            EditText editText = (EditText) findViewById(R.id.editText1);
            final TextView textView = (TextView) findViewById(R.id.textView);
             final String input= editText.getText().toString();
             new Thread(new Runnable(){
                 InetAddress ip;
                ip = InetAddress.getByName(input);
                final boolean reach= ip.isReachable(5000);
                runOnUiThread(new Runnable() {
                    textView.setText("real ?"+reach);
                });
             }).start(); 



                   textView.setText("real ?"+reach);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
    });
}   
}  

关于java - android ping InetAddress 和 editText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13323222/

相关文章:

Android - 在构建项目时遇到多个错误

java - Android Studio - 在现有的旧项目中启用 native C++ 调试 (card.io Android Source)

java - 对数组列表进行排序和搜索

java - JAXB/XJC 生成 JAXBElement<String> 而不仅仅是 String(以处理 null 大小写)

android - fragment 中的 setContentView

android - 如何使用 Eclipse 找出 Android list 文件中缺少的 Activity ?

java - 与 T 不兼容的类型

安卓打印 Intent

没有堆栈的 Java "Thread-2"会阻止终止

android - 为标签 LinearLayout 找到了意外的命名空间前缀 "xmlns"