2011-11-01 67 views
4

如何停止「ping」?以下代碼是我嘗試的方式,但失敗。如何停止由android.exe中的run.exec()啓動的進程

private class pingWifi implements Runnable { 
      Process p = null; 
    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     /* 
     * WifiInfo info=mWifiManager.getConnectionInfo(); int 
     * ip=info.getIpAddress(); String ips=Formatter.formatIpAddress(ip); 
     */ 
     System.out.println("pingWifi runnable"); 
     String[] shell = new String[] { "/system/bin/sh", "-c", " " }; 
     Runtime run = Runtime.getRuntime(); 

     shell[2] = "ping " + ipAddress; 
     try { 
      p = run.exec(shell); 
      if (p.waitFor() != 0) { 
       if (p.exitValue() == 1) { 
        byte[] buff = new byte[1024]; 
        InputStream is = p.getErrorStream(); 
        int c; 
        c = is.read(buff, 0, 1024); 
        System.out.println("ping error: " + new String(buff)); 
       } 
      } else { 
       byte[] buff = new byte[1024]; 
       InputStream is = p.getInputStream(); 
       int c; 
       c = is.read(buff, 0, 1024); 
       System.out.println("ping result: " + new String(buff)); 
       // wait for hardware 
      } 
     } catch (Exception e) { 
      // TODO: handle exception 
      e.printStackTrace(); 
     } 

    } 
void stopProcess() { 
     if (p != null) { 
      p.destroy(); 
     }else{ 
      System.out.println("stopProcess: p==null"); 
     } 
    } 



    } 
private pingWifi mpingWifi = new pingWifi(); 
    Thread wifiThread = new Thread(mpingWifi); 
      wifiThread.start(); 

在onPause中我調用mpingWifi.stopProcess(),結果是「stopProcess:p == null」。我仍然可以在「ps」列表中找到ping進程。

我也認爲使用「pkill ping」命令。但是在Android shell中不支持「pkill」命令。我的目標是在「home或back」鍵事件發生之前ping不是「停止」。謝謝!

回答

3

嘗試覆蓋後退按鈕並調用Process.destroy()。

例子:

public void onBackPressed() { 
p.destroy(); 
} 
+0

@kioboar謝謝您的答覆。什麼是p? – Judy

+0

@Judy p在你的代碼'Process p = null'。 – kikoboar

+0

但我得到「p是空的」。我認爲「ping 192.168.11.3」這個進程總是在運行,並且不會將它指向p。所以p是空的。這樣對嗎? – Judy

相關問題