Create a method like below :
public boolean checkInternet() {
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = conMan.getNetworkInfo(0).getState();
State wifi = conMan.getNetworkInfo(1).getState();
if (mobile == NetworkInfo.State.CONNECTED || wifi== NetworkInfo.State.CONNECTED)
return true;
else
return false;
}
In Activity or Service, you can do this :
if(CheckInternet)
{
// do your work
}
else
{
Thread t = new Thread() {
@Override
public void run() {
try
{
//check if connected!
while (!checkInternet())
{
//Wait to connect
Thread.sleep(5000);
}
//do Your Work here
} catch (Exception e) {
}
}
};
t.start();
}
Also add the following permission to the AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />