2011-11-01 25 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

相关问题