当前位置: 首页 > 知识库问答 >
问题:

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

孔茂
2023-03-14

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

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

共有2个答案

施玉宸
2023-03-14

这样的方法会奏效:

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;
    }

我已经从这里复制了这段代码(我理解代码-我只是为了方便用户而在这里添加代码,管理员告诉我应该这样做,并将原始帖子记入贷方)。就我个人而言,我会将其分为两个功能,一个用于移动,一个为wifi,但这取决于您的选择。

孟鸿德
2023-03-14

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

一些静态变量:

/**
 * 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
        }
    }
}
 类似资料:
  • 我需要检查的设备是否有互联网连接,我搜索一些例子,但当我复制和粘贴的代码,我总是得到错误或不推荐的函数。我也不明白我必须把检查连接的方法放在哪里,因为我需要检查viewModel中的internet连接来发出一些请求,而我找到的所有方法都在参数中有上下文,而我无法在viewModel中获得上下文。 我尝试了这段代码,但我不明白我必须把它放在哪里,我得到 有人能给我解释一下怎么开这张支票吗?

  • 我试着从这个答案(被接受的答案)。我可以使用“PING”方法,但用户界面变黑了,因为它说它会阻止用户界面线程。它看起来不太好,令人不安,所以我尝试使用第二种方法“连接到互联网上的套接字”,但我不知道如何使用Kotlin中的类。 这是android studio将Java转换为kotlin的结果 但是我不知道如何使用它。我试过这样做: 它不起作用,导致了一个错误。它说我必须通过“消费者”。 我的问题

  • Android我的设备与wifi连接,但如果wifi已连接,但这些没有互联网连接,该怎么做 以下是我尝试检查是否没有互联网连接的代码 当无法访问互联网时,它总是返回true

  • 若要使用PS Vita与互联网连接,需先准备无线通信的环境。 若您的住家等地无法通过无线通信,可使用公众无线LAN服务(Hotspot)在公众场所与互联网连接。 公众无线LAN服务的使用方法与费用会因该服务的提供者而异。详细请询问该服务的提供者。 使用Wi-Fi连接 若要使用Wi-Fi与互联网连接,需准备以下内容。此外,接入点的设定通常会通过电脑进行。 与网络服务商签订合约 接入点或无线路由器 接

  • 问题内容: 当我尝试在iPhone上检查互联网连接时,出现了很多错误。谁能帮我解决这个问题? 代码: 代码错误: 如果无法读取,则错误1表示: “ Int”不可转换为“ SCNetworkReachabilityFlags” 错误2和3: 找不到接受提供的参数的’init’的重载 问题答案: 为了解决注释中提到的4G问题,我已使用@AshleyMills可达性实现作为参考并重写了Swift 3.1

  • 你好,我有一个应用程序,有两个活动:主页面和详细页面。 当有互联网连接时,用户可以从主页面导航到详细信息页面。当没有网络连接时,他不能这样做。 问题是:当我进入详细信息页面并关闭wifi时,我想完成此活动,我如何实现此功能?我在主要活动类中检查过类似这样的内容: 当我启动有互联网或没有互联网的应用程序时,它都可以正常工作,但是当我在运行时关闭wifi时,它不起作用。 无论如何,谢谢你!

  • 可确认目前连接的接入点信息或网络的连接状态。

  • 进行与互联网间的连接测试,并显示结果。 名称* 目前使用的互联网连接之连接名称 SSID* 接入点的SSID 获取IP地址 显示是否可获取IP地址 互联网连接 显示是否可与互联网连接 登陆PlayStation®Network 显示是否能登陆PlayStation®Network NAT类型 显示PS Vita与互联网的连接方式 使用游戏的通信功能等时,可确认与其它PS Vita间的连接稳定性。