BroadcastReceiver的时候WiFi或3G网络状态改变 [英] BroadcastReceiver when wifi or 3g network state changed

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

问题描述

我开始做开发一个应用程序,只要手机连接到无线网络,将更新数据库。我实现了一个服务的BroadcastReceiver 将运行服务(它会告诉我的是使用的是何种网络),但问题是我不知道在清单文件中添加了什么,开始的BroadcastReceiver 网​​络状态发生变化时或者当它连接到某种网络

I started do develop an app which will update 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>

在您的接收器的标签。

In your receiver tag.

或者,如果你想要更多的控制权,之前注册的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

广播意图的行动,表明无线网络已启用,禁用,启用,禁用,还是个未知数。一个额外的提供了这种状态为int。另额外提供了previous状态,如果有的话。

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对象的形式的新的状态。如果新的状态连接,额外的附加可提供的接入点的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

此外,你需要指定内部清单标签正确的权限:

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

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

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