处理 Android 中的互联网连接变化
问题集中在需要一个可以监视互联网连接变化的广播接收器,因为现有代码仅检测连接更改。
为了解决此问题,这里有另一种方法:
<code class="java">public class NetworkUtil { public static final int TYPE_WIFI = 1; public static final int TYPE_MOBILE = 2; public static final int TYPE_NOT_CONNECTED = 0; public static int getConnectivityStatus(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) return TYPE_WIFI; if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) return TYPE_MOBILE; } return TYPE_NOT_CONNECTED; } }</code>
此方法确定设备是否连接到 WiFi 或移动数据。
<code class="java">public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { int status = NetworkUtil.getConnectivityStatus(context); if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction()) { if (status == NetworkUtil.TYPE_NOT_CONNECTED) { // Handle loss of internet connectivity } else { // Handle restoration of internet connectivity } } } }</code>
此广播接收器监视连接状态变化并根据当前状态触发操作。请记住在 AndroidManifest.xml 中包含适当的权限并注册接收器:
<code class="xml"><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <receiver android:name="NetworkChangeReceiver" android:label="NetworkChangeReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver></code>
以上是如何处理 Android 中的互联网连接变化?的详细内容。更多信息请关注PHP中文网其他相关文章!