javascriptjavaandroidandroid-studio.class-file

how to create check NetworkConnectionStatus in class file and use in mainactivity


add that in .class file and use in MainActivity.java how to create check NetworkConnectionStatus in class file and use in mainactivity


Private void checkNetworkConnectionStatus()   {
        boolean wifiConnected;
        boolean mobileConnected;
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
        if (activeInfo != null && activeInfo.isConnected()){ //connected with either mobile or wifi
            wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
            mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
            if (wifiConnected){ //wifi connected

            }
            else if (mobileConnected){ //mobile data connected

            }
        }
        else { //no internet connection

        }
    }

Solution

  • Just supply context while calling it on another class.

    First Declare this globally in your MainActivity.

    Context context = this;
    

    This is how you call your class supplied by your current activity context.

    new CheckNet().checkNetworkConnectionStatus(context);
    

    then change your class with method that require parameter: context

    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    
    class CheckNet {
    
        void checkNetworkConnectionStatus(Context context) {
            boolean wifiConnected;
            boolean mobileConnected;
            ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
            if (activeInfo != null && activeInfo.isConnected()) { //connected with either mobile or wifi
                wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
                mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
                if (wifiConnected) { //wifi connected
    
                } else if (mobileConnected) { //mobile data connected
    
                }
            } else { //no internet connection
    
            }
        }
    
    }