Android 进行PING包说白了实际上就是调用shell的一个脚本
而ping实际上是在我们手机或PAD的/system/bin/目录下。
MainActivity文件
package com.example.pingtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends Activity implements View.OnClickListener {
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btPing:
String ipAddr = mIpAddr.getText().toString();
if(ipAddr.equals("")){
Toast.makeText(MainActivity.this,"请填写IP地址",Toast.LENGTH_SHORT).show();
}else{
Process process = null;
String result = "";
try {
process = Runtime.getRuntime().exec("ping -c 3 "+ipAddr);
// int status = process.waitFor();
// if (status == 0) {
// result="success";
// }
// else
// {
// result=Integer.toString(status);
// }
InputStream input = process.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){
buffer.append(line);
mTextView.append(line+"\r\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
private Button mPing;//ping包按钮
private EditText mIpAddr;//ip地址输入框
private TextView mTextView;//系统返回
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIpAddr = (EditText)findViewById(R.id.ed_ipaddr);
mTextView = (TextView)findViewById(R.id.ping_content);
mPing =(Button)findViewById(R.id.btPing);
mPing.setOnClickListener(this);
}
}
layout文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dip"
android:orientation="horizontal"
android:id="@+id/main_linear_top">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:singleLine="true"
android:id="@+id/ed_ipaddr"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/ping"
android:id="@+id/btPing"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/main_linear_top"
android:background="#FF000000"
android:id="@+id/ping_content"
android:textColor="#FFFFFFFF"
/>
</RelativeLayout>
PS试过魅族的手机 发现直接通过adb shell 方式进行ping不被允许 猜测可能是非原生系统的原因。