Friday, 20 September 2013

Check internet connection in android .


 public boolean InternetAvailable() {
   
  Thread t = new Thread(new Runnable() {
  

   @Override
   public void run() {
    // while(isStopMe){
    System.out.println("This is inside ................. :");
    try {
     if (!checkConnection()) {
      System.out.println("No Internet Connectivity");
      isInternet = false;
      System.out.println("First");
     } else {
      if (inetAddr()) {
       System.out.println("Net Connectivity is Present");
       isInternet = true;
       System.out.println("Second");
      } else {
       if (mobileConnect()) {
        System.out.println("THIRD");
        if (inetAddr()) {
         System.out
           .println("Net Connectivity is Present");
         isInternet = true;
         System.out.println("FOURTH");
        } else {
         System.out
           .println("No Internet Connectivity");
        isInternet = false;
         System.out.println("FIFTH");
        }
       } else {
        System.out.println("No Internet Connectivity");
        isInternet = false;
        System.out.println("SIX");
       }
      }
     }
    } catch (Exception ex) {
     System.out.println("Leak ko catch");
    }
    
   }
  });
  t.start();
  try {
   t.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return isInternet;
 }
 
 
 public boolean checkConnection() {
  boolean connected = false;
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  if (cm != null) {
   NetworkInfo[] netInfo = cm.getAllNetworkInfo();
   for (NetworkInfo ni : netInfo) {
    if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni
      .getTypeName().equalsIgnoreCase("MOBILE"))
      & ni.isConnected() & ni.isAvailable()) {
     connected = true;
    }
   }
  }
  return connected;
 }

 public boolean inetAddr() {
  boolean x1 = false;
  
  try {
   Socket s = new Socket();
   s.connect(new InetSocketAddress("ntp-nist.ldsbc.edu",37),3000);
   InputStream is = s.getInputStream();
   
   Scanner scan = new Scanner(is);
   
   while(scan.hasNextLine()){
    
    System.out.println(scan.nextLine());
    x1 = true;
   }
  } catch (IOException e) {
   
   x1 = false;
   
  }
  return x1;
 }
 public boolean mobileConnect() {
  boolean conn = false;
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNet = cm
    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
  if (activeNet != null) {
   conn = true;
  } else {
   conn = false;
  }
  return conn;
 }

No comments:

Post a Comment