Android 判断是否能真正上网

Android里判断是否能够上网,经常使用的是以下方法:html

 

?网络

1app

2spa

3.net

4code

5htm

6ip

7ci

8get

9

10

11

12

13

14

/**

 * 检测网络是否链接

 *

 * @return

 */

private boolean isNetworkAvailable() {

    // 获得网络链接信息

    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    // 去进行判断网络是否链接

    if (manager.getActiveNetworkInfo() != null) {

        return manager.getActiveNetworkInfo().isAvailable();

    }

    return false;

}

 

 

可是,有时候咱们链接上一个没有外网链接的WiFi或者须要输入帐号和密码才能连接外网的网络,就会出现虽然网络可用,可是外网却不能够访问。针对这种状况,通常的解决办法就是ping一个外网,若是能ping通就说明能够真正上网,代码以下

 

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

@author sichard

     @category 判断是否有外网链接(普通方法不能判断外网的网络是否链接,好比链接上局域网)

     @return

     */ 

    public static final boolean ping() { 

     

        String result = null

        try 

                String ip = "www.baidu.com";// ping 的地址,能够换成任何一种可靠的外网 

                Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次 

                // 读取ping的内容,能够不加 

                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的状态 

                int status = p.waitFor(); 

                if (status == 0) { 

                        result = "success"

                        return true

                else 

                        result = "failed"

                

        catch (IOException e) { 

                result = "IOException"

        catch (InterruptedException e) { 

                result = "InterruptedException"

        finally 

                Log.d("----result---""result = " + result); 

        

        return false;

相关文章
相关标签/搜索