问题:
我们能否监控 Android 设备上的网络连接变化并捕获事件当网络离线时?
答案:
是的,Android 中可以监听网络连接变化。详细实现如下:
1.创建广播接收器:
<code class="java">public class ConnectionChangeReceiver extends BroadcastReceiver { ... @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); // Check for active network and mobile network changes ... } ... }</code>
2.声明权限:
<code class="xml"><!-- Required to monitor network connectivity changes --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /></code>
3.在AndroidManifest.xml中注册接收器:
<code class="xml"><receiver android:name="com.blackboard.androidtest.receiver.ConnectionChangeReceiver" android:label="NetworkConnection"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver></code>
说明:
广播接收器注册自身以侦听来自系统的“CONNECTIVITY_CHANGE”广播。当网络状态发生变化时,会触发 onReceive() 方法,接收方可以检查当前网络状态并做出相应响应。
以上是如何检测 Android 中的网络连接变化?的详细内容。更多信息请关注PHP中文网其他相关文章!