android - 在 android 中检查慢速互联网连接和区分网络连接和实际互联网连接的有效方法

标签 android android-internet

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

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

最佳答案

如果你想知道什么时候你有一个活跃的互联网连接,做这样的事情:

一些静态变量:

/**
 * 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
        }
    }
}

关于android - 在 android 中检查慢速互联网连接和区分网络连接和实际互联网连接的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25309603/

相关文章:

java - 日历给错误的一天

java - 关于Build.VERSION.SDK_INT

android - 检测android设备是否连接到互联网

android - picasso 从 URL 下载多张图片

android - 检测 Android 上是否有可用的 Internet 连接

java - 无法从 android.app.Application 转换为自定义类型

java - 使用 JRE 1.8 或更高版本运行 Android Studio

android - Android 应用的 token 授权

java - 在 UI 线程之外运行东西

android - 启用互联网连接 - Android Wear