首先弄个网络广播
NetworkChangeReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
private List<NetStateChangeObserver> mObservers = new ArrayList<>();
private int mType = -1;
private static boolean isRegister = false;
private static class InstanceHolder {
private static final NetworkChangeReceiver INSTANCE = new NetworkChangeReceiver();
}
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
int connectivityStatus = NetworkUtil.getConnectivityStatus(context);
notifyObservers(connectivityStatus);
}
}
private static void registerReceiver(Context context) {
if (!isRegister){
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(InstanceHolder.INSTANCE, intentFilter);
isRegister = true;
}
}
private static void unRegisterReceiver(Context context) {
if (isRegister) {
context.unregisterReceiver(InstanceHolder.INSTANCE);
}
}
public static void registerObserver(Context context,NetStateChangeObserver observer) {
if (observer == null) {
return;
}
if (!isRegister){
registerReceiver(context);
if (!InstanceHolder.INSTANCE.mObservers.contains(observer)) {
InstanceHolder.INSTANCE.mObservers.add(observer);
}
}
}
public static void unRegisterObserver(Context context,NetStateChangeObserver observer) {
if (observer == null) {
return;
}
unRegisterReceiver(context);
if (InstanceHolder.INSTANCE.mObservers == null) {
return;
}
InstanceHolder.INSTANCE.mObservers.remove(observer);
}
private void notifyObservers(int networkType) {
if (mType == networkType) {
return;
}
mType = networkType;
if (networkType == NetworkUtil.TYPE_MOBILE) {
for (NetStateChangeObserver observer : mObservers) {
observer.onMobileConnect();
observer.onConnect();
}
} else if (networkType == NetworkUtil.TYPE_WIFI) {
for (NetStateChangeObserver observer : mObservers) {
observer.onWifiConnect();
observer.onConnect();
}
} else {
for (NetStateChangeObserver observer : mObservers) {
observer.onDisconnect();
}
}
;
}
public interface NetStateChangeObserver {
void onDisconnect();
void onMobileConnect();
void onWifiConnect();
void onConnect();
}
}
使用示例:
第一步:
class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>(),NetworkChangeReceiver.NetStateChangeObserver
第二步:
在onCreate方法中:
NetworkChangeReceiver.registerObserver(mContext,this)
第三步:
override fun onDisconnect() {
Log.i("netChange","onDisconnect")
}
override fun onMobileConnect() {
Log.i("netChange","onMobileConnect")
}
override fun onWifiConnect() {
Log.i("netChange","onWifiConnect")
}
/**
* @desc : 网络连接上,不管是wifi还是数据
*
**/
override fun onConnect() {}
在这里面写你的逻辑代码即可。
第四步:
别忘了,在onDestroy注册掉你的网络监听
网友评论