wifi 或 3g 网络状态改变时的广播接收器 [英] BroadcastReceiver when wifi or 3g network state changed

查看:39
本文介绍了wifi 或 3g 网络状态改变时的广播接收器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,只要手机连接到 WiFi,它就会更新数据库.我已经实现了一个 ServiceBroadcastReceiver,它们将运行 Service(它会告诉我正在使用什么网络),但问题是我不知道在 manifest 文件中添加什么来启动 BroadcastReceiver 当网络状态改变或连接到某种网络时

I have an app which updates the database whenever the phone is connected to WiFi. I have implemented a Service and BroadcastReceiver which will run the Service (it will tell me what network is in use), but the problem is I don't know what to add in the manifest file to start BroadcastReceiver when the network state changes or when it connects to some kind of network

推荐答案

您需要

<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>

在您的 receiver 标签中.

或者,如果您想对其进行更多控制,请在注册 BroadcastReceiver 之前进行设置:

Or if you want more control over it, before registering BroadcastReceiver set these up:

final IntentFilter filters = new IntentFilter();
filters.addAction("android.net.wifi.WIFI_STATE_CHANGED");
filters.addAction("android.net.wifi.STATE_CHANGE");
super.registerReceiver(yourReceiver, filters);

WIFI_STATE_CHANGED

广播 指示 Wi-Fi 已启用、禁用、启用、禁用或未知.一个额外的提供这个状态作为一个int.另一个额外的提供以前的状态(如果有).

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.

STATE_CHANGE

广播 指示 Wi-Fi 连接状态已更改.一个额外的以 NetworkInfo 对象的形式提供新状态.如果新状态是 CONNECTED,额外的附加项可以提供接入点的 BSSID 和 WifiInfo.作为字符串

Broadcast <intent-action> indicating that the state of Wi-Fi connectivity has changed. One extra provides the new state in the form of a NetworkInfo object. If the new state is CONNECTED, additional extras may provide the BSSID and WifiInfo of the access point. as a String

此外,您需要在 manifest 标签内指定正确的权限:

Also, you'll need to specify the right permissions inside manifest tag:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

要检查连接,您可以使用 ConnectivityManager,因为它会告诉您可用的连接类型.

To check connectivity, you can use ConnectivityManager as it tells you what type of connection is available.

ConnectivityManager conMngr = (ConnectivityManager)this.getSystemService(this.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = conMngr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = conMngr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

这篇关于wifi 或 3g 网络状态改变时的广播接收器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆