Android to determine if there is an extranet connection _android

Source: Internet
Author: User
Tags stringbuffer

Android to determine whether the Internet, commonly used is the following methods:

/**
 * Detect whether the network is connected
 * 
 * @return/
Private Boolean isnetworkavailable () {
  //Get network connection Information
  Connectivitymanager manager = (Connectivitymanager) getsystemservice (context.connectivity_service);
  To determine if the network is connected if
  (manager.getactivenetworkinfo ()!= null) {return
    manager.getactivenetworkinfo (). IsAvailable ();
  }
  return false;
}

There are times when we connect to a WiFi or cable that doesn't have an extranet connection, and the current Android SDK doesn't recognize the situation, and the general solution is to ping an extranet.

/* @author Suncat * @category To determine whether there is an extranet connection (the common method can not determine whether the network is connected, such as LAN) * @return/public static final Boolean ping () { 
  String result = null;  try {String IP = "www.baidu.com";//Ping's address, which can be replaced by any reliable extranet Process P = runtime.getruntime (). EXEC ("Ping-c 3 
      -W-M "+ IP"//Ping URL 3 times/Read the contents of Ping, can not add inputstream input = P.getinputstream (); 
      BufferedReader in = new BufferedReader (new InputStreamReader (input)); 
      StringBuffer StringBuffer = new StringBuffer (); 
      String content = ""; 
      while (content = In.readline ())!= null) {stringbuffer.append (content); 
      } log.d ("------ping-----", "Result content:" + stringbuffer.tostring ()); 
      Ping's status int status = P.waitfor (); 
          if (status = = 0) {result = "success"; 
      return true; 
      else {result = "failed"; 
  The catch (IOException e) {result = ' ioexception '; catch (Interruptedexception e) {
      result = "Interruptedexception"; 
  finally {LOG.D ("----Result---", ' result = ' + result);
return false;

 }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.