How to stop the process launched by run.exec () in android

How to stop ping? The following code is the way I'm trying, but it does not work.

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(); 

In onPause, I call mpingWifi.stopProcess (), the result is "stopProcess: p == null". And I can still find the ping process in the ps list.

I am also thinking of using the "pkill ping" command. but the "pkill" command is not supported in the Android shell. My goal is ping does not โ€œstopโ€ until the key event โ€œat home or backโ€ occurs. Thanks!

+4
source share
1 answer

Try overriding the back button and click Process.destroy () in it.

Example:

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

Source: https://habr.com/ru/post/1379079/


All Articles