Tuesday, November 9, 2010

Check Internet Connection

import YourPackageName

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.widget.Toast;

class CheckInternetConnection
{
public Context context = null;
public ProgressDialog dialogProcess = null;

public CheckInternetConnection(Context ctx)
{
this.context = ctx;
}

@SuppressWarnings("unchecked")
public boolean CheckInternet()
{
ConnectivityManager connec = (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if (wifi.isConnected())
{
return true;
}
else if (!mobile.isConnected())
{
Toast.makeText(context,"No Internet Connection",5000).show();
return false;
}
else
{
new AsyncCheckInternet().execute();
}

return false;
}

private class AsyncCheckInternet extends AsyncTask
{
@Override
protected void onPreExecute()
{
dialogProcess = ProgressDialog.show(context, "","Checking Internet Connection...",true);
}

@Override
protected Boolean doInBackground(Object... arg0)
{
try
{
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url
.openConnection();
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(3000); // This is time limit if the connection time limit
urlc.connect();
if (urlc.getResponseCode() == 200)
{
return true;
}
}
catch (MalformedURLException e1)
{
e1.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}

@Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
dialogProcess.dismiss();
}

}
}