For most of the android applications, we face the problem where we have to continuously check the internet connection.
We can use Broadcast Receiver to to detect the change in network connectivity.
below code shows the implementation for the same.
public class ConnectivityReceiver extends BroadcastReceiver { private static boolean firstConnect = true; @Override public void onReceive(Context context, Intent intent) { final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null) { boolean isConnected = activeNetInfo.isConnected(); boolean isWiFi = activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI; boolean isMobile = activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE; if (firstConnect) { firstConnect = false; //checks for the type of network, device is connected to. if (isConnected && isWiFi) { if(!Utilities.isReleaseMode(context)){ Toast.makeText(context, "Connected to Internet", Toast.LENGTH_SHORT).show(); } Log.i("Wifi Network connected", "wifi Network connected"); } else if (isConnected && isMobile) { if(!Utilities.isReleaseMode(context)) { Toast.makeText(context, "Connected to Internet", Toast.LENGTH_SHORT).show(); } Log.i("Mobile Network ", "mobile Network connected"); } } } else { firstConnect = true; // Log.i("Network Disconnected", "Network Disconnected"); }
}
Here i have used boolean variable firstConnect to avoid entering the loop mutipletimes.
No comments:
Post a Comment