2017-06-27 107 views
0

我試圖在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.com8.8.8.8的地址。但是,如果我ping一個不響應的地址,如intel.comlalalalalalalaandroid.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.

但我沒有得到這些在我的應用程序......我在這裏失蹤的任何東西?

+0

請注意,Android設備不需要「ping」實用程序,更不用說在特定的文件系統位置。 – CommonsWare

+0

我知道,目前這不是問題。我有點兒在擺弄。 – MadClown

+0

如果你通過'adb shell'而不是你的PC運行命令(這可能會運行不同的ping實現),你會得到什麼? – adelphus

回答

0

根據文檔,AsyncTasks只能執行一次。嘗試在可運行的計時器中重新初始化它。

public void InitializeTimerTask() { 
    timerPingTask = new timerPingTask() { 
     public void run() { 
      handler.post(new Runnable() { 
       public void run() { 
        new PingAsyncTask().execute(); 
       } 
      }); 
     } 
+0

謝謝,但這已在Activity的代碼中處理完畢。 執行任務多次工作。 – MadClown