简体   繁体   English

Android是连接到互联网方法的设备

[英]Android is device connected to the internet method

I want to create a method which tells if the device is online. 我想创建一个方法来告诉设备是否在线。 As far as I understand ConnectivityManager tells only if the device is connected to a network. 据我了解,ConnectivityManager仅告诉设备是否已连接到网络。 This doesn't mean that the device is connected to the internet. 这并不意味着设备已连接到互联网。 To ensure that the device is online I'm using InetAddress.getByName("google.com").isReachable(3); 为确保设备在线,我使用了InetAddress.getByName("google.com").isReachable(3); but I can't use it on the main thread. 但是我不能在主线程上使用它。 I can create a separate thread to check the connectivity and then use a callback function but is there another way? 我可以创建一个单独的线程来检查连接性,然后使用回调函数,但是还有另一种方法吗? I don't want my app to do anything before it is connected. 我不希望我的应用在连接之前执行任何操作。 Do you have any solutions? 你有什么解决方案? Thank you! 谢谢!

try this: 尝试这个:

public static boolean isOnline(Context context) {

    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnected()) {
        return true;
    }

    return false;
}

With any networking, there isn't a guaranteed way to check whether or not you are connected to an endpoint without actually sending data. 对于任何网络,都无法保证在不实际发送数据的情况下检查您是否已连接到端点。 Even if the device is connected to a network, has an ip address, recently received data, etc, it doesn't mean that you still have a connection. 即使设备已连接到网络,具有ip地址,最近接收到的数据等,也并不意味着您仍在连接。

I would suggest allowing the user to progress into your application as much as possible, queuing up the requests to your server in the background whilst a connection is established. 我建议允许用户尽可能多地进入您的应用程序,在建立连接的同时在后台将对服务器的请求排队。 Use the same framework to resend data if the connection is lost whilst the user is using the app. 如果在用户使用应用程序时连接断开,请使用相同的框架重新发送数据。 Make the connection to the server as transparent to the user as possible, unless it fails to connect after ~1 minute 使与服务器的连接对用户尽可能透明,除非在1分钟后连接失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM