Hi Guys !!! Hope all is well
Today I am going to discuss about Ping in Android. Ping an IP Address used to determine if your device is connected to the internet. Below is the Ping Features :
- Ping is a network utility used to test reachable of an IP address or a host.
- It can measure the packet trip time which is called latency.
- Ping uses ICMP for request packets and waits for an ICMP response.
- Ping is useful to check a server's availability.
I am going to create one sample Android app to ping external IP address or AP Gateway IP Address. This application by default send 2 ping every minute. But it is configurable. You can increase or decrease ping rate either via UI or adb shell command. You can download this app from my Github account.
public boolean pingToServer(String host) {
//host = "192.168.1.65";
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 " + host);
int exitValue = ipProcess.waitFor();
Log.d(LOG_TAG, "ping host: "+host+" exitValue: "+exitValue);
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
Above code used Android RunTime API to ping. It is very easy way to ping without going to much in details and no need to app get signed
public void startAlarm(int pingValue) {
final Handler h = new Handler();
Log.d(LOG_TAG, "MyPingService: PingCount : "+pingValue);
long startTime = System.currentTimeMillis();
int intervalTime = 30*1000;
if(pingValue<=10){
intervalTime = (60/pingValue)*1000;
}
final int delay = intervalTime; //milliseconds
Log.d(LOG_TAG, "MyPingService: Ping interval Time : "+delay);
h.postDelayed(new Runnable(){
public void run(){
//send Ping
if(IP_Address!=null){
if (pingToServer(IP_Address))
Log.d(LOG_TAG, "ping is reachable");
else
Log.d(LOG_TAG, "ping is not reachable");
}else {
if (pingToServer(getGatewayIP()))
Log.d(LOG_TAG, "ping is reachable");
else
Log.d(LOG_TAG, "ping is not reachable");
}
if (!stopHandler) {
h.postDelayed(this, delay);
}
}
}, intervalTime);
}
Above code set pinging on predefined value example :- 4 ping/minute. I am using Handler API postDelayed method to set repeating task.
I have added Android Service to keep this app running in background . You can download my project and check all source code in details.
Thanks
Saurabh
Happy Coding !!!