一、在Activity的Xml 中
在这里只需要一个TextView即可
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/tv_net"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
二、在Activity中
public class MainActivity extends AppCompatActivity implements NetEvent {
private TextView tv_net;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
tv_net = (TextView) findViewById(R.id.tv_net);
NetBroadCastReceiver netBroadCastReceiver=new NetBroadCastReceiver();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(netBroadCastReceiver,intentFilter);
netBroadCastReceiver.setNetEvent(this);
}
@Override
public void onNetChanged(int state) {
switch (state){
case -1:
tv_net.setText("当前无网络状态");
break;
case 1:
tv_net.setText("当前状态为wifi");
break;
case 0:
tv_net.setText("当前状态为移动网络");
break;
}
}
}
三、创建工具类
public class NetUtil {
private static final int NETWORK_NONE = -1;
private static final int NETWORK_MOBILE = 0;
private static final int NETWORK_WIFI = 1;
public static int getNetWorkState(Context context) {
// 得到连接管理器对象
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
return NETWORK_WIFI;
} else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
return NETWORK_MOBILE;
}
} else {
return NETWORK_NONE;
}
return NETWORK_NONE;
}
}
四、创建接口
public interface NetEvent {
void onNetChanged(int state);
}
五、创建广播
public class NetBroadCastReceiver extends BroadcastReceiver {
private NetEvent netEvent;
private boolean equals;
private int state;
@Override
public void onReceive(Context context, Intent intent) {
//过滤下广播
equals = intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION);
//如果为true 说明接受到的广播就是网络状态发生变化的广播
if (equals) {
state = NetUtil.getNetWorkState(context);
netEvent.onNetChanged(state);
}
}
public void setNetEvent(NetEvent netEvent) {
this.netEvent = netEvent;
}
}