wifi或3g网络状态更改时的BroadcastReceiver

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



MYYA
浏览 525回答 3
3回答

三国纷争

这是我要在连接更改时得到通知的方法。您定义一个BroadCastReceiver来接收广播。public class NetworkChangeReceiver extends BroadcastReceiver {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onReceive(Context context, Intent intent) {&nbsp; &nbsp; &nbsp; &nbsp; ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);&nbsp; &nbsp; &nbsp; &nbsp; NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);&nbsp; &nbsp; &nbsp; &nbsp; NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);&nbsp; &nbsp; &nbsp; &nbsp; boolean isConnected = wifi != null && wifi.isConnectedOrConnecting() ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mobile != null && mobile.isConnectedOrConnecting();&nbsp; &nbsp; &nbsp; &nbsp; if (isConnected) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("Network Available ", "YES");&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("Network Available ", "NO");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}您还必须BroadcastReceiver在清单文件中进行定义,并按过滤ConnectivityChange。<receiver android:name=".NetworkChangeReceiver" >&nbsp; &nbsp; &nbsp; &nbsp; <intent-filter>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />&nbsp; &nbsp; &nbsp; &nbsp; </intent-filter></receiver>

白板的微信

补充@Dantalian的答案。从Android Nougat开始,您不应在清单上声明接收器,因为它不会接收CONNECTIVITY_ACTION广播。您应该改为使用Context.registerReceiver(Receiver, Intent)方法注册您的接收器。
打开App,查看更多内容
随时随地看视频慕课网APP