Android 中的 Internet 连接更改侦听器
连接更改的默认广播接收器监视网络可用性,但不一定监视 Internet 连接。为了解决这个限制,让我们探索一种更全面的方法。
互联网连接监控
利用以下实用程序类来确定当前的互联网连接状态:
<code class="java">public class NetworkUtil { public static int getConnectivityStatus(Context context) { // Check for active network ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); // Determine network type (Wi-Fi, mobile, or not connected) if (activeNetwork != null) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { return TYPE_WIFI; } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { return TYPE_MOBILE; } } return TYPE_NOT_CONNECTED; } // Convert network status to string representation (Wi-Fi, mobile, or not connected) public static int getConnectivityStatusString(Context context) { int conn = NetworkUtil.getConnectivityStatus(context); int status = 0; if (conn == NetworkUtil.TYPE_WIFI) { status = NETWORK_STATUS_WIFI; } else if (conn == NetworkUtil.TYPE_MOBILE) { status = NETWORK_STATUS_MOBILE; } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) { status = NETWORK_STATUS_NOT_CONNECTED; } return status; } }</code>
用于 Internet 连接更改的广播接收器
创建侦听 Internet 连接更改的广播接收器:
<code class="java">public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { int status = NetworkUtil.getConnectivityStatusString(context); if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) { if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) { // Handle loss of Internet connection } else { // Handle recovery of Internet connection } } } }</code>
AndroidManifest.xml 配置
在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>
通过实施这种方法,您可以监控Internet连接的变化并做出相应的响应,从而确保网络的稳定性在突然失去互联网连接的情况下应用程序的功能。
以上是如何在 Android 中创建可靠的互联网连接更改侦听器?的详细内容。更多信息请关注PHP中文网其他相关文章!