The Android system already does that for you. Instead of constantly polling the phone for the network state, register BroadcastReceivers for WiFi and network state changes and process the Intents sent by the system when the WiFi or network state changes.
You should make a BroadcastReceiver that will be triggered when the connectivity status has changed.
NetworkChangeReceiver.java
public class NetworkChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, final Intent intent)
{
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
NetworkUtil.java
public class NetworkUtil
{
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context)
{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork)
{
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context)
{
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI)
{
status = "Wifi enabled";
}
else if (conn == NetworkUtil.TYPE_MOBILE)
{
status = "Mobile data enabled";
}
else if (conn == NetworkUtil.TYPE_NOT_CONNECTED)
{
status = "Not connected to Internet";
}
return status;
}
}
Add Required Permission and Receiver in Androidmanifest.xml