简体   繁体   中英

How to check if mobile network is connected to the internet or not in android

How to check if packet data of the mobile is connected or not. Because when I enable the mobile data option on my android app even without any load in my simcard it always connects. My problem is how to validate if the there is an internet connection or not in my android app.

btw here is my code.

    ConnectivityManager cm = (ConnectivityManager)this.GetSystemService(Context.ConnectivityService);



    NetworkInfo nf = cm.ActiveNetworkInfo;
    if (nf != null && nf.IsConnected == true)
    {
//connected
    }
    else
    {
//not connected
    }

But in this code. Even if i'm out of load. My application show i' still connected. Help Pls..

Try this:

boolean internetCheck;
internetCheck = isInternetAvailable(this);
if (internetCheck) {
                //Internet available
            } else {
                //No Internet available         }  
    /**
         * 
         * Method to check internet connection is available
         */

        public static boolean isInternetAvailable(Context context) {
            boolean haveConnectedWifi = false;
            boolean haveConnectedMobile = false;
            boolean connectionavailable = false;

            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();

            NetworkInfo informationabtnet = cm.getActiveNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                try {

                    if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                        if (ni.isConnected())
                            haveConnectedWifi = true;
                    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                        if (ni.isConnected())
                            haveConnectedMobile = true;
                    if (informationabtnet.isAvailable()
                            && informationabtnet.isConnected())
                        connectionavailable = true;

                } catch (Exception e) {
                    // TODO: handle exception
                    System.out.println("Inside utils catch clause , exception is"
                            + e.toString());
                    e.printStackTrace();

                }
            }
            return haveConnectedWifi || haveConnectedMobile;
        }

Try this

//call web service
    ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);
    boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
    boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
    //check Internet connection
    if(internet||wifi)
    {
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show(); 
    }else{
                    Toast.makeText(this, "Not Connected", Toast.LENGTH_SHORT).show(); 
            }       

Also add following permissions to your Manifest file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Try this one.        
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        boolean isActive=activeNetworkInfo != null && activeNetworkInfo.isConnected();
               if(isActive)
                 {
               System.out.print("Connection Establied");
                  }
                else{
                    System.out.print("Connection not Establied");
                     }

Try this

public class ConnectionDetector {
private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}

public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null) 
              for (int i = 0; i < info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}
}

And in activity file

     ConnectionDetector cd= new ConnectionDetector(context);

   boolean  isInternetPresent = cd.isConnectingToInternet();

it will return true if internet is present

I think in your case this link may help you

How can I receive a notification when the device loses network connectivity?

The best way to check internet connection is to send a request and see whether you are getting back anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM