【问题标题】:Effective way to check for slow internet connection and differentiate between network connection and actual internet connection in android在 android 中检查慢速互联网连接并区分网络连接和实际互联网连接的有效方法
【发布时间】:2014-10-08 04:43:03
【问题描述】:

如何检查设备是否已连接到互联网或仅连接到外部 wifi 网络?因为如果设备连接到外部 wifi 网络,即使没有网络连接,NetworkInfo 也会返回 true。

当设备连接到 wifi 但无法访问互联网时,我的应用程序的网络连接检查类返回 true,但应用程序崩溃,但无法访问相应的 http url。

【问题讨论】:

  • NetworkInfo 会告诉您设备以某种方式连接到某个网络。然后,您可以尝试例如加载谷歌网页以检查您是否可以访问互联网。
  • @Wildcopper-但是如果互联网连接太慢怎么办?我应该在后台线程中添加超时吗?

标签: android android-internet


【解决方案1】:

如果您想知道您何时拥有有效的互联网连接,请执行以下操作:

一些静态变量:

/**
 * Set the number of retries when reestablishing Internet connection.
 */
private static int retryConnectionNumber = 0;

/**
 * The maximum number of retries allowed for Internet connection.
 */
private final static int CONNECTION_RETRY_MAX = 5;

/**
 * The timeout of the HTTP request when checking for Internet connection.
 */
private final static int REQUEST_TIMEOUT = 2000;

检查网络是否可用的方法:

private static void isNetworkAvailable(final Handler handler,
            final int timeout) {
        new Thread() {
            private boolean responded = false;

            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL("http://your_server_addres.com");
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }
                String host = "";
                if (null != url) {
                    host = url.getHost();
                }

                Log.i("NetworkCheck", "[PING] host: " + host);
                Process process = null;
                try {
                    process = new ProcessBuilder()
                            .command("/system/bin/ping", "-c 1",
                                    "-w " + (timeout / 1000), "-n", host)
                            .redirectErrorStream(true).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                InputStream in = process.getInputStream();
                StringBuilder s = new StringBuilder();
                int i;

                try {
                    while ((i = in.read()) != -1) {
                        s.append((char) i);

                        if ((char) i == '\n') {
                            Log.i("NetworkCheck",
                                    "[PING] log: " + s.toString());
                            if (s.toString().contains("64 bytes from")) {
                                // If there were a response from the server at
                                // all, we have Internet access
                                responded = true;
                            }
                            s.delete(0, s.length());
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    // Destroy the PING process
                    process.destroy();

                    try {
                        // Close the input stream - avoid memory leak
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    // Send the response to the handler, 1 for success, 0
                    // otherwise
                    handler.sendEmptyMessage(!responded ? 0 : 1);
                }
            }
        }.start();
    }

处理程序:

/**
 * Handler used that receives the connection status for the Internet.
 * If no active Internet connection will retry #CONNECTION_RETRY_MAX times
 */
private static Handler listenForNetworkAvailability = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (msg.what != 1) { // code if not connected
            Log.i("NetworkCheck", "not connected");

            if (retryConnectionNumber <= CONNECTION_RETRY_MAX) {
                Log.i("NetworkCheck", "checking for connectivity");
                Here you could disable & re-enable your WIFI/3G connection before retry

                // Start the ping process again with delay
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isNetworkAvailable(listenForNetworkAvailability, REQUEST_TIMEOUT);
                    }
                }, 5000);
                retryConnectionNumber++;
            } else {
                Log.i("NetworkCheck", "failed to establish an connection");
                // code if not connected
            }
        } else {            
            Log.i("NetworkCheck", "connected");
            retryConnectionNumber = 0;
            // code if connected
        }
    }
}

【讨论】:

    【解决方案2】:

    这样的事情会起作用:

    private boolean haveNetworkConnection() {
            boolean haveConnectedWifi = false;
            boolean haveConnectedMobile = false;
    
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                    if (ni.isConnected())
                        haveConnectedWifi = true;
                if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    if (ni.isConnected())
                        haveConnectedMobile = true;
            }
            return haveConnectedWifi || haveConnectedMobile;
        }
    

    我已经从here 复制了这段代码(我理解代码 - 我只是在此处添加代码以方便用户使用 + 管理员告诉我你应该这样做并记入原始帖子)。就我个人而言,我会将其分为两种功能,一种用于移动设备,另一种用于 wifi,但您可以自行选择。

    【讨论】:

    • @apmartin1991-在存在网络但没有互联网的情况下,此代码仍将返回 true。应用仍然会崩溃。
    • isConnected() 表示是否存在网络连通性,是否可以建立连接和传递数据。如果你发生了崩溃,那么它可能是由于不同的原因而导致的崩溃。你能把你的logcat贴出来让我们看看吗?
    • @apmartin1991-问题是我无法随意生成该条件。有时当wifi连接没有互联网访问时,应用程序会崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 2022-12-01
    • 2012-06-12
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    相关资源
    最近更新 更多