Android 网络状态的变化监听目前主要有两种方式,一种是通过 ConnectivityManager 网络连接管理类来注册监听网络状态回调,另一种则是通过广播来实现。
1、通过 ConnectivityManager 来实现
- 创建 ConnectivityManager 对象
ConnectivityManager connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE);
- 添加注册回调方法
在 Android SDK 版本 21- 26 之间,调用 ConnectivityManager 的 registerNetworkCallback 方法
/**
* Registers to receive notifications about all networks which satisfy the given
* {@link NetworkRequest}. The callbacks will continue to be called until
* either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
* called.
*
* @param request {@link NetworkRequest} describing this request.
* @param networkCallback The {@link NetworkCallback} that the system will call as suitable
* networks change state.
* The callback is invoked on the default internal Handler.
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
public void registerNetworkCallback(@NonNull NetworkRequest request,
@NonNull NetworkCallback networkCallback) {
registerNetworkCallback(request, networkCallback, getDefaultHandler());
}
其中包含2个参数
NetworkRequest:主要是用来定义一个网络请求,用于请求一个网络或者侦听请求改变
NetworkRequest.Builder builder = new NetworkRequest.Builder();
NetworkRequest request = builder.build();
NetworkCallback:用来回调网络变化信息
//定义一个类去继承 NetworkCallback,里面有很多方法可以实现,这里主要实现 onAvailable 当网络可以、onLost 当网络不可用
public class FTNetWorkCallback extends ConnectivityManager.NetworkCallback {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
judgeNetState();
}
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
}
}
最后传入参数即可
NetworkRequest.Builder builder = new NetworkRequest.Builder();
NetworkRequest request = builder.build();
connectivityManager.registerNetworkCallback(request, networkCallback);
在 Android 系统版本大于 26 时,直接传入回调类即可
connectivityManager.registerDefaultNetworkCallback(networkCallback);
2、通过广播来实现
因为在 Android 8.0 之后取消了很多静态广播,所以使用该方法要注意系统的版本。
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(networkReceiver, intentFilter);
public class FTNetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//添加判断网络状态的方法
}
}
来源:CSDN
作者:未来探路人
链接:https://blog.csdn.net/android_hdh/article/details/104064302