NetStateChangeReceiver.java
1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.wd.common.net;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.wd.base.log.Logger;
import com.wd.capability.network.constant.NetConstant;
import com.wd.capability.network.constant.EventConstants;
import com.wd.foundation.bean.livedate.NetStateMessage;
import com.wd.foundation.wdkitcore.livedata.LiveDataBus;
/**
* 网络状态监听
*
* @author shishuangxi_wd
* @date 2022/7/9 16:42
*/
public class NetStateChangeReceiver extends BroadcastReceiver {
private final String TAG = "NetStateChangeReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
// 获取联网状态的NetworkInfo对象
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (info != null) {
String type = "2";
// 如果当前的网络连接成功并且网络连接可用
if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
Logger.t(TAG).d("连接上WiFi");
type = NetConstant.NET_WIFI_TYPE;
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
Logger.t(TAG).d("连接上移动网络数据");
type = NetConstant.NET_CELL_TYPE;
}
} else {
type = NetConstant.NET_ERROR_TYPE;
Logger.t(TAG).d("网络断开");
}
LiveDataBus.getInstance()
.with(EventConstants.NETWORK_STATE_CHANGE)
.postValue(new NetStateMessage(type));
}
}
}
}