Skip to content

Instantly share code, notes, and snippets.

@Viyu

Viyu/PingUtil Secret

Last active January 3, 2016 05:09
Show Gist options
  • Save Viyu/d0df67fb40be217638a3 to your computer and use it in GitHub Desktop.
Save Viyu/d0df67fb40be217638a3 to your computer and use it in GitHub Desktop.
A util class to ping a given target.
public class PingUtil {
private static final int MSG_TIME_OUT = 0;
private static final int TIME_OUT = 80000;
private static class PingHandler extends Handler {
private WeakReference<PingUtil> pingHelperWeakRef;
PingHandler(PingUtil pingHelper) {
pingHelperWeakRef = new WeakReference<PingUtil>(pingHelper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == MSG_WHAT_TIME) {
PingUtil pingHelper = pingHelperWeakRef.get();
if (pingHelper != null) {
pingHelper.timeOut();
}
}
}
}
private PingHandler handler = null;
private PingCallback callback = null;
private CmdTask cmdTask = null;
public PingHelper(String target, PingCallback pingCallback) {
handler = new PingHandler(this);
this.callback = pingCallback;
//
handler.sendEmptyMessageDelayed(MSG_TIME_OUT, TIME_OUT);
cmdTask = new CmdTask();
cmdTask.execute("ping -c 2 " + target);//-c 2 measn ping twice.
}
private void timeOut() {
if(cmdTask != null) {
cmdTask.cancel(true);
}
if (handler != null) {
handler.removeMessages(MSG_TIME_OUT);
}
}
private class CmdTask extends AsyncTask<String, Void, Boolean> {
Process proc = null;
@Override
protected Boolean doInBackground(String... cmdArray) {
boolean flag = false;
if (cmdArray == null || cmdArray.length < 1) {
flag = false;
} else {
Runtime run = Runtime.getRuntime();
try {
proc = run.exec(cmdArray[0]);
int result = proc.waitFor();
if (result == 0) {
flag = true;
} else {
flag = false;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
proc.destroy();
}
}
return flag;
}
@Override
protected void onCancelled() {
super.onCancelled();
if (proc != null) {
try {
proc.destroy();
} catch (Throwable t) {
t.printStackTrace();
}
}
if (callback != null) {
callback.onPingFinished(false);
}
if (handler != null) {
handler.removeMessages(MSG_TIME_OUT);
}
}
@Override
protected void onPostExecute(Boolean result) {
if (callback != null) {
callback.onPingFinished(result);
}
if (handler != null) {
handler.removeMessages(MSG_TIME_OUT);
}
}
}
public interface PingCallback {
public void onPingFinished(boolean flag);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment