0

I use the isconnectInternet() method to control the mobile phone internet connection in my all of classes. I do that, but it is duplicated in every class. How I can write it once and use it everywhere in the project?

  public boolean isConnected(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netinfo = cm.getActiveNetworkInfo();

    if (netinfo != null && netinfo.isConnectedOrConnecting()) {
        android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        return (mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting());
    } else
        return false;
}

This is my method to control the internet

if(isConnected){

   if there is internet conn.
} 
else{
  there is no internet do samething

}
Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
bruslee
  • 3
  • 1

2 Answers2

1

You can write this method in another class and call it when you want it.

public class Common {

    public static boolean isConnected(Context context) {

         ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo netinfo = cm.getActiveNetworkInfo();

              if (netinfo != null && netinfo.isConnectedOrConnecting()) {
               android.net.NetworkInfo wifi=cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
               android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        return (mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting());
    } else
        return false;
    }
}

and call it by class name and method name

if(Common.isConnected ){

   if there is internet conn.
 } 
 else{
     there is no internet do samething

 }
A.s.ALI
  • 1,992
  • 3
  • 22
  • 54
Yıldırım
  • 757
  • 10
  • 24
0

Static Methods are your friend in this case. Change:

public boolean isConnected(Context context) {

to:

public static boolean isConnected(Context context) {

This changes the method so that it no longer relies on an instance of a class, so you can access it from any other class. As a result, this changes your check method to:

if(MyClass.isConnected(context)){
    //if there is internet conn.
} 
else{
    //there is no internet do something
}

Bear in mind that this works in your particular example as you're only relying on a context that is passed in as an argument. If you declare a function as static, you'll no longer be able to access the member variables of that class unless they too are declared static.

Michael Dodd
  • 10,102
  • 12
  • 51
  • 64