Android实现ping功能
Andriod实现ping功能,输入需要ping的地址、ping的数据包个数和大小、以及每隔多久ping一次,ping功能比较耗时,所以在开启的子线程中进行,然后把ping结果发送到主线程中更新Textview显示结果。对结果可以有两种操作,一是复制,二是保存到本地SD卡中,方便以后查看。
资源可以从http://download.youkuaiyun.com/detail/offerfinder/8903779免费下载,下面是效果图:
主界面:
结果:
对结果进行的操作:
下面看具体代码:
布局文件:
/PING测试/res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="IP地址"
android:textSize="18sp" />
<EditText
android:id="@+id/edit_ip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="www.baidu.com" />
<TextView
android:id="@+id/tv_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送数据包的数目(个)"
android:textSize="18sp" />
<EditText
android:id="@+id/edit_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:text="4" />
<TextView
android:id="@+id/tv_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送数据包的大小(byte)"
android:textSize="18sp" />
<EditText
android:id="@+id/edit_size"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:text="64" />
<TextView
android:id="@+id/tv_5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送数据包的间隔时间(s)"
android:textSize="18sp" />
<EditText
android:id="@+id/edit_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1" />
<Button
android:id="@+id/btn_ping"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_key_selector"
android:text="PING" />
</LinearLayout>
主Activity:
/PING测试/src/com/example/ping_test/MainActivity.java
package com.example.ping_test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
Button btn_ping;
EditText et_ip, et_count, et_size, et_time;
String ip, count, size, time;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_ping = (Button) findViewById(R.id.btn_ping);
et_ip = (EditText) findViewById(R.id.edit_ip);
et_count = (EditText) findViewById(R.id.edit_count);
et_size = (EditText) findViewById(R.id.edit_size);
et_time = (EditText) findViewById(R.id.edit_time);
btn_ping.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// String ip = et_ip.getText().toString();
// String result = PingHost.Ping(ip);
// tv_show.setText(result);
// System.out.println("result ============= " + result);
ip = et_ip.getText().toString();
count = et_count.getText().toString();
size = et_size.getText().toString();
time = et_time.getText().toString();
String countCmd = " -c " + count + " ";
String sizeCmd = " -s " + size + " ";
String timeCmd = " -i " + time + " ";
String ip_adress = ip;
String ping = "ping" + countCmd + timeCmd + sizeCmd + ip_adress;
Intent intent = new Intent();
intent.setClass(MainActivity.this, PingResult1.class);
// new一个Bundle对象,并将要传递的数据传入
Bundle bundle = new Bundle();
bundle.putString("ping", ping);
bundle.putString("ip", ip);
bundle.putString("count", count);
bundle.putString("size", size);
bundle.putString("time", time);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
显示ping结果Activity:
/PING测试/src/com/example/ping_test/PingResult1.java
package com.example.ping_test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class PingResult1 extends Activity {
private int CHOOSE = 0;
TextView tv_show;
String lost = "";// 丢包
String delay = "";// 延迟
String ip_adress = "";// ip地址
String countCmd = "";// ping -c
String sizeCmd = "", timeCmd = "";// ping -s ;ping -i
String result = "";
private static final String tag = "TAG";// Log标志
int status = -1;// 状态
String ping, ip, count, size, time;
long delaytime = 0;
// Myhandler handler=null;
Handler handler1 = null;
Thread a = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pingresult);
tv_show = (TextView) findViewById(R.id.tv_show);
Intent intent2 = this.getIntent();
Bundle bundle2 = intent2.getExtras();
ping = bundle2.getString("ping");
ip = bundle2.getString("ip");
count = bundle2.getString("count");
time = bundle2.getString("time");
size = bundle2.getString("size");
delaytime = (long) Double.parseDouble(time);
Log.i(tag, "====MainThread====:" + Thread.currentThread().getId());
tv_show.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(
PingResult1.this);
builder.setTitle("请选择操作");
String[] items = { "复制", "保存到SD卡" };
builder.setSingleChoiceItems(items, 0,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
CHOOSE = which;
}
});
builder.setNegativeButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
// Toast.makeText(PingResult1.this,
// "which="+which+"\nChoose="+CHOOSE,
// Toast.LENGTH_SHORT).show();
switch (CHOOSE) {
case 0:
ClipboardManager cm = (ClipboardManager) PingResult1.this
.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(tv_show.getText());
Toast.makeText(PingResult1.this, "复制成功!",
Toast.LENGTH_SHORT).show();
break;
case 1:
Date date = new Date();
SimpleDateFormat sfd = new SimpleDateFormat(
"yyyy-MM-dd HH.mm.ss");
String time = sfd.format(date) + ".txt";
String text = tv_show.getText().toString();
FileUtils fileUtils = new FileUtils();
fileUtils.writeToSDFromStr(fileUtils.SDPATH
+ "/PING/", time, text);
Toast.makeText(PingResult1.this,
"保存成功!" + fileUtils.SDPATH,
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
CHOOSE = 0;
}
});
builder.setPositiveButton("取消", null);
builder.show();
}
});
handler1 = new Handler() {// 创建一个handler对象 ,用于监听子线程发送的消息
public void handleMessage(Message msg)// 接收消息的方法
{
// String str = (String) msg.obj;// 类型转化
// tv_show.setText(str);// 执行
switch (msg.what) {
case 10:
String resultmsg = (String) msg.obj;
tv_show.append(resultmsg);
Log.i(tag, "====handlerThread====:"
+ Thread.currentThread().getId());
Log.i(tag, "====resultmsg====:" + msg.what);
Log.i(tag, "====resultmsg====:" + resultmsg);
break;
default:
break;
}
}
};
a = new Thread()// 创建子线程
{
public void run() {
// for (int i = 0; i < 100; i++) {
// try {
// sleep(500);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// Message msg = new Message();// 创建消息类
// msg.obj = "线程进度 :" + i;// 消息类对象中存入消息
// handler1.sendMessage(msg);// 通过handler对象发送消息
// }
delay = "";
lost = "";
Process process = null;
BufferedReader successReader = null;
BufferedReader errorReader = null;
DataOutputStream dos = null;
try {
// 闃诲澶勭悊
process = Runtime.getRuntime().exec(ping);
// dos = new DataOutputStream(process.getOutputStream());
Log.i(tag, "====receive====:");
String command = "ping" + countCmd + timeCmd + sizeCmd
+ ip_adress;
// dos.write(command.getBytes());
// dos.writeBytes("\n");
// dos.flush();
// dos.writeBytes("exit\n");
// dos.flush();
// status = process.waitFor();
InputStream in = process.getInputStream();
OutputStream out = process.getOutputStream();
// success
successReader = new BufferedReader(
new InputStreamReader(in));
// error
errorReader = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
String lineStr;
while ((lineStr = successReader.readLine()) != null) {
Log.i(tag, "====receive====:" + lineStr);
Message msg = handler1.obtainMessage();
msg.obj = lineStr + "\r\n";
msg.what = 10;
msg.sendToTarget();
result = result + lineStr + "\n";
if (lineStr.contains("packet loss")) {
Log.i(tag, "=====Message=====" + lineStr.toString());
int i = lineStr.indexOf("received");
int j = lineStr.indexOf("%");
Log.i(tag,
"====丢包率====:"
+ lineStr.substring(i + 10, j + 1));//
lost = lineStr.substring(i + 10, j + 1);
}
if (lineStr.contains("avg")) {
int i = lineStr.indexOf("/", 20);
int j = lineStr.indexOf(".", i);
Log.i(tag,
"====平均时延:===="
+ lineStr.substring(i + 1, j));
delay = lineStr.substring(i + 1, j);
delay = delay + "ms";
}
// tv_show.setText("丢包率:" + lost.toString() + "\n" +
// "平均时延:"
// + delay.toString() + "\n" + "IP地址:");// +
// getNetIpAddress()
// + getLocalIPAdress() + "\n" + "MAC地址:" +
// getLocalMacAddress() + getGateWay());
sleep(delaytime * 1000);
}
// tv_show.setText(result);
while ((lineStr = errorReader.readLine()) != null) {
Log.i(tag, "==error======" + lineStr);
// tv_show.setText(lineStr);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (dos != null) {
dos.close();
}
if (successReader != null) {
successReader.close();
}
if (errorReader != null) {
errorReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
}
};
a.start();
}
}
用于往SD卡写txt文本文件的工具类文件:
/PING测试/src/com/example/ping_test/FileUtils.java
package com.example.ping_test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
public class FileUtils {
public String SDPATH;
public String getSDPATH() {
return SDPATH;
}
public void setSDPATH(String sDPATH) {
SDPATH = sDPATH;
}
public FileUtils() {
// 得到当前外部存储设备的目录
// SDCARD
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
// 在SD卡上创建文件
public File creatSDfile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
// 在SD卡上创建目录
public File creatSDDir(String dirName) {
File dir = new File(SDPATH + dirName);
dir.mkdir();
return dir;
}
// 判断SD卡上的文件是否存在
public boolean isFileExist(String fileName) {
File file = new File(SDPATH + fileName);
return file.exists();
}
// 把InputStream里的数据写入到SD卡中去
public File writeToSDFromIuput(String path, String fileName,
InputStream input) {
File file = null;
OutputStream output = null;
try {
creatSDDir(path);
file = creatSDfile(path + fileName);
output = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
while ((input.read(buffer)) != -1) {
output.write(buffer);
}
output.flush();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
output.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
return file;
}
public void writeToSDFromStr(String path,String fileName,String str){
File file=null;
FileOutputStream fos=null;
try {
file=new File(path, fileName);
fos=new FileOutputStream(file);
// fos.write(str.getBytes());
// fos.write("\r\n".getBytes());
// fos.write("I am lilu".getBytes());
// fos.close();
PrintWriter pw=new PrintWriter(fos,true);
pw.println(str);;
pw.close();
Log.i("TAG", "====保存成功====:");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}