Better approach would be to use android.net.ConnectivityManager class. Register the receiver and monitor broadcasts.
private class ConnectionMonitor extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
return;
}
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
NetworkInfo aNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (!noConnectivity) {
if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
|| (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
// Handle connected case
}
} else {
if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
|| (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
// Handle disconnected case
}
}
}
}
private synchronized void startMonitoringConnection() {
IntentFilter aFilter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mConnectionReceiver, aFilter);
}
private synchronized void stopMonitoringConnection() {
unregisterReceiver(mConnectionReceiver);
}
where
mConnectionReceiver = new ConnectionMonitor();