How to Ping a Url in an Android Service

How to ping a URL in an Android Service?

I think if you just want to ping an url, you can use this code :

try {
URL url = new URL("http://" + params[0]);

HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30); // Timeout is in seconds
urlc.connect();

if (urlc.getResponseCode() == 200) {
Main.Log("getResponseCode == 200");
return new Boolean(true);
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

And, if you want to have the equivalent of a ping, you can put a System.currentTimeMillis() before and after the call, and calculate the difference.

hopes that helps

code snippet found in here

android ping a URL (not to open)

HttpURLConnection connection = null;
try {
URL u = new URL("http://www.google.com/");
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
System.out.println("" + code);
// You can determine on HTTP return code received. 200 is success.
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}

Android - Check internet connection by pinging url address

try this create a class that extends AsyncTask

public class CheckInternet extends AsyncTask<Void, Void, Boolean>{
private static final String TAG = "CheckInternet";
private Context context;

public CheckInternet(Context context) {
this.context = context;

}

@Override
protected Boolean doInBackground(Void... voids) {
Log.d(TAG, "doInBackground: ");
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();

if (isConnected) {
if ( executeCommand()) return true;
}
return false;
}

private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c "+"www.google.com");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}


Related Topics



Leave a reply



Submit