1

我想在 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按钮时,它就会从应用程序中出来,为什么?

4

2 回答 2

0

我猜你对 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();
            }   
        }
    });
}   
}  
于 2016-07-23T03:01:21.057 回答
-1

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

谢谢

于 2013-03-25T20:32:55.313 回答