【问题标题】:android ping InetAddress and editTextandroid ping InetAddress 和editText
【发布时间】:2012-11-10 15:11:10
【问题描述】:

我想在 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键,应用程序就出来了,为什么?

【问题讨论】:

  • 如果不分析代码 - 您的应用程序很可能只是崩溃了。查看logcat 输出,看看发生了什么,不要猜测!

标签: java android eclipse ping inetaddress


【解决方案1】:

我猜你的 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();
            }   
        }
    });
}   
}  

【讨论】:

  • 两个“Runnable”都错过了 public void run() {...} 方法。
【解决方案2】:

如果您仍在寻找这个问题的答案,但您的应用程序崩溃的原因是因为您不允许执行网络操作,例如 ip = InetAddress.getByName(输入);请在 mainactivity 中创建另一个类并让它扩展 AsyncTask 并在那里执行您的网络操作。

谢谢

【讨论】:

    猜你喜欢
    • 2014-09-25
    • 2018-02-18
    • 1970-01-01
    • 2014-08-18
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多