user934820
user934820

Reputation: 1178

Check if 3g,4g is connected android

I am using below code to check if any kind of connectivity is available on mobile or tablet. It is working fine with WiFi and GPRS. Unfortunately I have no 3g access, therefore I cannot check if this code is working. If any of you please can confirm it? And how much it effect battery life?

 private  boolean chkConnectivity() {
    boolean isConnected = false;

    ConnectivityManager connManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if( mobile.isAvailable() && mobile.getDetailedState() == NetworkInfo.DetailedState.CONNECTED ){
        Toast.makeText(ctx, "3g", Toast.LENGTH_SHORT).show();
        return true;
    }
    if (mWifi.isAvailable() && mWifi.getDetailedState() == NetworkInfo.DetailedState.CONNECTED ) {
        Toast.makeText(ctx, "WiFi", Toast.LENGTH_SHORT).show();
        return true;
    }
    try {
        TelephonyManager mgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        int networkType = mgr.getNetworkType();
        if (networkType == TelephonyManager.NETWORK_TYPE_GPRS){
            Class cmClass = Class.forName(connManager.getClass().getName());
            Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
            method.setAccessible(true);
            isConnected = (Boolean)method.invoke(connManager);
            if (isConnected){
                Toast.makeText(ctx, "GPRS", Toast.LENGTH_SHORT).show();
                return isConnected;
            }
        }
        Toast.makeText(ctx, "No connection", Toast.LENGTH_SHORT).show();
        return isConnected;

    } catch (Exception e) {
        return false;
    }

}

Upvotes: 0

Views: 875

Answers (1)

KISHORE_ZE
KISHORE_ZE

Reputation: 1466

Sorry I was late.

This is how your app runs. No problem in it.

Without data

Image2

With data enter image description here

Upvotes: 2

Related Questions