我想在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/