在Android Java中执行Ping任务
问题描述:
我试图在Android中将AsyncTask实现为Ping实用程序。以下基本上是我的doInBackground
功能。在Android Java中执行Ping任务
mProcess = Runtime.getRuntime().exec("/system/bin/ping -c 6 " + url);
try {
InputStream in = mProcess.getInputStream();
OutputStream out = mProcess.getOutputStream();
byte[] buffer = new byte[ 1024 ];
int count;
while((count = in.read(buffer)) != -1){
mPOut.write(buffer, 0, count);
publishProgress();
Log.d("PING TASK", "PING.... PING....");
if(isCancelled()) {
return null;
}
}
out.close();
in.close();
mPOut.close();
mPIn.close();
} finally {
mProcess.destroy();
mProcess = null;
Log.d("PING TASK", "DONE");
}
} catch(IOException e) {
Log.d("PING TASK", e.getMessage());
}
return null;
它按预期工作,但只有当我平安做出响应,如android.com
或8.8.8.8
的地址。但是,如果我ping一个不响应的地址,如intel.com
或lalalalalalalaandroid.com
(我没有完全检查那个)。
如果我在我的PC上执行ping -c 6 intel.com
,我至少得到第一行PING intel.com (13.91.95.74) 56(84) bytes of data.
或Ping request could not find host lalalalalalalaandroid.com Please check the name and try again.
。
但我没有得到这些在我的应用程序......我在这里失踪的任何东西?
答
根据文档,AsyncTasks只能执行一次。尝试在可运行的计时器中重新初始化它。
public void InitializeTimerTask() {
timerPingTask = new timerPingTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
new PingAsyncTask().execute();
}
});
}
+0
谢谢,但这已在Activity的代码中处理完毕。 执行任务多次工作。 – MadClown
请注意,Android设备不需要“ping”实用程序,更不用说在特定的文件系统位置。 – CommonsWare
我知道,目前这不是问题。我有点儿在摆弄。 – MadClown
如果你通过'adb shell'而不是你的PC运行命令(这可能会运行不同的ping实现),你会得到什么? – adelphus