正在为Android 2.2开发Ping应用程序。
我尝试了我的代码,它可以工作,但是仅在本地IP中,这也是我想对外部服务器执行ping操作的问题。
这是我的代码:
private OnClickListener milistener = new OnClickListener() { public void onClick(View v) { TextView info = (TextView) findViewById(R.id.info); EditText edit = (EditText) findViewById(R.id.edit); Editable host = edit.getText(); InetAddress in; in = null; // Definimos la ip de la cual haremos el ping try { in = InetAddress.getByName(host.toString()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Definimos un tiempo en el cual ha de responder try { if (in.isReachable(5000)) { info.setText("Responde OK"); } else { info.setText("No responde: Time out"); } } catch (IOException e) { // TODO Auto-generated catch block info.setText(e.toString()); } } };
Ping 127.0.0.1-> OK Ping 8.8.8.8(Google DNS)->超时
我也将以下行放在清单XML中:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
谁能告诉我我做错了什么?
获取ip命中的布尔值
public Boolean getInetAddressByName(String name) { AsyncTask<String, Void, Boolean> task = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... params) { try { return InetAddress.getByName(params[0]).isReachable(2000); } catch (Exception e) { return null; } } }; try { return task.execute(name).get(); } catch (InterruptedException e) { return null; } catch (ExecutionException e) { return null; } }