Android实现ping功能
生活随笔
收集整理的這篇文章主要介紹了
Android实现ping功能
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Android實(shí)現(xiàn)ping功能
? Andriod實(shí)現(xiàn)ping功能,輸入需要ping的地址、ping的數(shù)據(jù)包個(gè)數(shù)和大小、以及每隔多久ping一次,ping功能比較耗時(shí),所以在開啟的子線程中進(jìn)行,然后把ping結(jié)果發(fā)送到主線程中更新Textview顯示結(jié)果。對(duì)結(jié)果可以有兩種操作,一是復(fù)制,二是保存到本地SD卡中,方便以后查看。
? 資源可以從http://download.csdn.net/detail/offerfinder/8903779免費(fèi)下載,下面是效果圖:
主界面:
結(jié)果:
對(duì)結(jié)果進(jìn)行的操作:
? 下面看具體代碼: 布局文件: /PING測(cè)試/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" ><TextViewandroid:id="@+id/tv_1"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="IP地址"android:textSize="18sp" /><EditTextandroid:id="@+id/edit_ip"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="www.baidu.com" /><TextViewandroid:id="@+id/tv_3"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="發(fā)送數(shù)據(jù)包的數(shù)目(個(gè))"android:textSize="18sp" /><EditTextandroid:id="@+id/edit_count"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="number"android:text="4" /><TextViewandroid:id="@+id/tv_4"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="發(fā)送數(shù)據(jù)包的大小(byte)"android:textSize="18sp" /><EditTextandroid:id="@+id/edit_size"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="number"android:text="64" /><TextViewandroid:id="@+id/tv_5"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="發(fā)送數(shù)據(jù)包的間隔時(shí)間(s)"android:textSize="18sp" /><EditTextandroid:id="@+id/edit_time"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="1" /><Buttonandroid: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測(cè)試/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;@Overridepublic 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() {@Overridepublic 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一個(gè)Bundle對(duì)象,并將要傳遞的數(shù)據(jù)傳入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結(jié)果Activity: /PING測(cè)試/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 -cString sizeCmd = "", timeCmd = "";// ping -s ;ping -iString result = "";private static final String tag = "TAG";// Log標(biāo)志int status = -1;// 狀態(tài)String ping, ip, count, size, time;long delaytime = 0;// Myhandler handler=null;Handler handler1 = null;Thread a = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubAlertDialog.Builder builder = new AlertDialog.Builder(PingResult1.this);builder.setTitle("請(qǐng)選擇操作");String[] items = { "復(fù)制", "保存到SD卡" };builder.setSingleChoiceItems(items, 0,new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog,int which) {// TODO Auto-generated method stubCHOOSE = which;}});builder.setNegativeButton("確定",new DialogInterface.OnClickListener() {@Overridepublic 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, "復(fù)制成功!",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() {// 創(chuàng)建一個(gè)handler對(duì)象 ,用于監(jiān)聽子線程發(fā)送的消息public void handleMessage(Message msg)// 接收消息的方法{// String str = (String) msg.obj;// 類型轉(zhuǎn)化// tv_show.setText(str);// 執(zhí)行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()// 創(chuàng)建子線程{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();// 創(chuàng)建消息類// msg.obj = "線程進(jìn)度 :" + i;// 消息類對(duì)象中存入消息// handler1.sendMessage(msg);// 通過handler對(duì)象發(fā)送消息// }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();// successsuccessReader = new BufferedReader(new InputStreamReader(in));// errorerrorReader = 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,"====平均時(shí)延:===="+ lineStr.substring(i + 1, j));delay = lineStr.substring(i + 1, j);delay = delay + "ms";}// tv_show.setText("丟包率:" + lost.toString() + "\n" +// "平均時(shí)延:"// + 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測(cè)試/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() {// 得到當(dāng)前外部存儲(chǔ)設(shè)備的目錄// SDCARDSDPATH = Environment.getExternalStorageDirectory() + "/";}// 在SD卡上創(chuàng)建文件public File creatSDfile(String fileName) throws IOException {File file = new File(SDPATH + fileName);file.createNewFile();return file;}// 在SD卡上創(chuàng)建目錄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里的數(shù)據(jù)寫入到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 exceptione.printStackTrace();} finally {try {output.close();} catch (Exception e2) {// TODO: handle exceptione2.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 exceptione.printStackTrace();}}}
結(jié)果:
對(duì)結(jié)果進(jìn)行的操作:
? 下面看具體代碼: 布局文件: /PING測(cè)試/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" ><TextViewandroid:id="@+id/tv_1"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="IP地址"android:textSize="18sp" /><EditTextandroid:id="@+id/edit_ip"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="www.baidu.com" /><TextViewandroid:id="@+id/tv_3"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="發(fā)送數(shù)據(jù)包的數(shù)目(個(gè))"android:textSize="18sp" /><EditTextandroid:id="@+id/edit_count"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="number"android:text="4" /><TextViewandroid:id="@+id/tv_4"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="發(fā)送數(shù)據(jù)包的大小(byte)"android:textSize="18sp" /><EditTextandroid:id="@+id/edit_size"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="number"android:text="64" /><TextViewandroid:id="@+id/tv_5"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="發(fā)送數(shù)據(jù)包的間隔時(shí)間(s)"android:textSize="18sp" /><EditTextandroid:id="@+id/edit_time"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="1" /><Buttonandroid: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測(cè)試/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;@Overridepublic 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() {@Overridepublic 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一個(gè)Bundle對(duì)象,并將要傳遞的數(shù)據(jù)傳入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結(jié)果Activity: /PING測(cè)試/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 -cString sizeCmd = "", timeCmd = "";// ping -s ;ping -iString result = "";private static final String tag = "TAG";// Log標(biāo)志int status = -1;// 狀態(tài)String ping, ip, count, size, time;long delaytime = 0;// Myhandler handler=null;Handler handler1 = null;Thread a = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubAlertDialog.Builder builder = new AlertDialog.Builder(PingResult1.this);builder.setTitle("請(qǐng)選擇操作");String[] items = { "復(fù)制", "保存到SD卡" };builder.setSingleChoiceItems(items, 0,new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog,int which) {// TODO Auto-generated method stubCHOOSE = which;}});builder.setNegativeButton("確定",new DialogInterface.OnClickListener() {@Overridepublic 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, "復(fù)制成功!",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() {// 創(chuàng)建一個(gè)handler對(duì)象 ,用于監(jiān)聽子線程發(fā)送的消息public void handleMessage(Message msg)// 接收消息的方法{// String str = (String) msg.obj;// 類型轉(zhuǎn)化// tv_show.setText(str);// 執(zhí)行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()// 創(chuàng)建子線程{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();// 創(chuàng)建消息類// msg.obj = "線程進(jìn)度 :" + i;// 消息類對(duì)象中存入消息// handler1.sendMessage(msg);// 通過handler對(duì)象發(fā)送消息// }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();// successsuccessReader = new BufferedReader(new InputStreamReader(in));// errorerrorReader = 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,"====平均時(shí)延:===="+ lineStr.substring(i + 1, j));delay = lineStr.substring(i + 1, j);delay = delay + "ms";}// tv_show.setText("丟包率:" + lost.toString() + "\n" +// "平均時(shí)延:"// + 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測(cè)試/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() {// 得到當(dāng)前外部存儲(chǔ)設(shè)備的目錄// SDCARDSDPATH = Environment.getExternalStorageDirectory() + "/";}// 在SD卡上創(chuàng)建文件public File creatSDfile(String fileName) throws IOException {File file = new File(SDPATH + fileName);file.createNewFile();return file;}// 在SD卡上創(chuàng)建目錄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里的數(shù)據(jù)寫入到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 exceptione.printStackTrace();} finally {try {output.close();} catch (Exception e2) {// TODO: handle exceptione2.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 exceptione.printStackTrace();}}}
總結(jié)
以上是生活随笔為你收集整理的Android实现ping功能的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机英语名词解释之软件工程篇
- 下一篇: java 英语简历模板下载 百度云_ja