这是检测 WiFi 网络连接的正确方法吗?

发布于 2024-11-05 14:00:43 字数 163 浏览 1 评论 0原文

我正在为 Android 制作一个应用程序,需要在设备连接到 WiFi 网络时做出反应,我目前正在尝试使用 BroadcastReceiver 来监视 android.net.ConnectivityManager.CONNECTIVITY_ACTION 来实现它 - 这种方式是否正确,或者有没有更合适的方法?

I'm making an application for Android that needs to react to when the device gets connected to a WiFi network, I'm currently trying to implement it using a BroadcastReceiver to monitor android.net.ConnectivityManager.CONNECTIVITY_ACTION - is this way correct, or is there a way that would be more appropriate?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撕心裂肺的伤痛 2024-11-12 14:00:43

@Jase,您需要注册才能接收 WifiManager.NETWORK_STATE_CHANGED_ACTION。该意图有一个额外的NetworkInfo。检查它以找到其状态。如果状态为 NetworkInfo.State.CONNECTED,则您已连接到网络。

有关实现此目的的示例代码,请查看此处

@Jase, You need to register to receive WifiManager.NETWORK_STATE_CHANGED_ACTION. The intent has a NetworkInfo extra. Examine it to find its state. If the state is NetworkInfo.State.CONNECTED, then you are connected to a network.

For sample code on achieving this, look here.

凉薄对峙 2024-11-12 14:00:43

看看 WifiManager.WIFI_STATE_CHANGED_ACTION

广播意图动作指示
Wi-Fi 已启用、禁用,
启用、禁用或未知。一
extra 将此状态作为 int 提供。
另一个额外提供了之前的
说明(如果有)。

WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION

广播意图动作指示
与请求者的连接
已经成立(现在是
可以执行 Wi-Fi 操作)
或与请求者的连接
已丢失。另一项额外提供的是
连接状态为布尔值,其中
true 表示已连接。

从广播中读取或在收到其中任何一个时进行检查,例如:

WifiManager wifi=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int state=wifi.getWifiState();

现在您可以检查状态,它将是

  • WIFI_STATE_DISABLED
  • WIFI_STATE_DISABLING
  • WIFI_STATE_ENABLED <-- 之一您可以发送/接收数据
  • WIFI_STATE_ENABLING
  • WIFI_STATE_UNKNOWN

Take a look at WifiManager.WIFI_STATE_CHANGED_ACTION

Broadcast intent action indicating
that Wi-Fi has been enabled, disabled,
enabling, disabling, or unknown. One
extra provides this state as an int.
Another extra provides the previous
state, if available.

and WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION

Broadcast intent action indicating
that a connection to the supplicant
has been established (and it is now
possible to perform Wi-Fi operations)
or the connection to the supplicant
has been lost. One extra provides the
connection state as a boolean, where
true means CONNECTED.

Read from the broadcast or do a check when you get any of them like:

WifiManager wifi=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int state=wifi.getWifiState();

Now you can check state, it will be one of

  • WIFI_STATE_DISABLED
  • WIFI_STATE_DISABLING
  • WIFI_STATE_ENABLED <-- With this you can send/receive data
  • WIFI_STATE_ENABLING
  • WIFI_STATE_UNKNOWN
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文