Android:监控互联网连接变化
为了监控互联网连接变化,Android 提供了 ConnectivityManager.NetworkCallback 类。与传统的 BroadcastReceiver 相比,这允许更精细的监听。实现方法如下:
<code class="java">public class ConnectivityMonitor extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { // Internet connectivity is available Log.d("Connectivity", "Internet connected"); } @Override public void onLost(Network network) { // Internet connectivity is lost Log.d("Connectivity", "Internet disconnected"); } }</code>
要注册此回调,您需要创建一个 ConnectivityManager 实例并调用 registerNetworkCallback 方法:
<code class="java">ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); connectivityManager.registerNetworkCallback(new NetworkRequest.Builder().build(), new ConnectivityMonitor());</code>
您也可以使用预定义的连接ConnectivityManager 的状态:
<code class="java">if (connectivityManager.getActiveNetworkInfo() != null) { // Connected to a network if (connectivityManager.getActiveNetworkInfo().isConnectedToWifi()) { // Connected via WiFi } else { // Connected via mobile data } } else { // Not connected to a network }</code>
完成后请记住取消注册回调:
<code class="java">connectivityManager.unregisterNetworkCallback(new ConnectivityMonitor());</code>
以上是如何监控 Android 应用程序中的互联网连接变化?的详细内容。更多信息请关注PHP中文网其他相关文章!