gpt4 book ai didi

java - NetworkInfo.isConnected() 和 NetworkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED 之间的区别。用什么?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:59:55 24 4
gpt4 key购买 nike

我想知道哪种方法可以准确地检查网络状态以成功连接。

最佳答案

所以如果我们看一下 source codeNetworkInfo.java 类中,您会看到网络详细状态被声明为 Enum,

public enum DetailedState {
/** Ready to start data connection setup. */
IDLE,
/** Searching for an available access point. */
SCANNING,
/** Currently setting up data connection. */
CONNECTING,
/** Network link established, performing authentication. */
AUTHENTICATING,
/** Awaiting response from DHCP server in order to assign IP address information. */
OBTAINING_IPADDR,
/** IP traffic should be available. */
CONNECTED,
/** IP traffic is suspended */
SUSPENDED,
/** Currently tearing down data connection. */
DISCONNECTING,
/** IP traffic not available. */
DISCONNECTED,
/** Attempt to connect failed. */
FAILED,
/** Access to this network is blocked. */
BLOCKED,
/** Link has poor connectivity. */
VERIFYING_POOR_LINK,
/** Checking if network is a captive portal */
CAPTIVE_PORTAL_CHECK
}

但是如果你阅读了这些 DetailedState 的评论,它会在下面说明这些

The fine-grained state of a network connection. This level of detail is probably of interest to few applications. Most should use android.net.NetworkInfo.State State instead.

NetworkInfo.java 类中的 isConnected() 方法仅检查 State.CONNECTED State

public boolean isConnected() {
synchronized (this) {
return mState == State.CONNECTED;
}
}

基本上如果你使用

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();

这应该足够了,因为上面的代码将查询 Activity 网络并确定它是否具有 Internet 连接。一旦知道,您就可以继续访问互联网资源。

关于java - NetworkInfo.isConnected() 和 NetworkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED 之间的区别。用什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55037991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com