本文介绍android的网络监控。
在项目中,我们往往要实时监控网络的状态,例如:1、你在看小视频,此时你的Wi-Fi断掉了,自动连上移动蜂窝网了,此时app就应该提示用户注意流量的使用。2、你想发起网络请求,但是你没连接网络,此时app也应该提示用户,如果发起网络请求,请打开网络等。具体监控步骤如下:
1、我们先创建个广播,用户接受网络变化发来的信息。
public class NetWorkBroadCastReceiver extends BroadcastReceiver {
private OnNetWorkWatchListener listener;
public NetWorkBroadCastReceiver(OnNetWorkWatchListener listenser) {
this.listener = listenser;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent !=null) {
if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
Utils.NetState state = Utils.NetworkState(context);
if (listener !=null) {
listener.onNetWorkChanged(state);
}
}
}
}
public interface OnNetWorkWatchListener {
/**
* 网络状态
*
* @param state
*/
void onNetWorkChanged(Utils.NetState state);
}
}
2、在BaseActivity中注册该广播,根据网络变化合理的提示用户,比如增加弹出框引导客户打开网络开关,关闭移动蜂窝开发,打开Wi-Fi开关等。
public abstract class BaseActivity extends FragmentActivity implements NetWorkBroadCastReceiver.OnNetWorkWatchListener {
private static final StringTAG = BaseActivity.class.getSimpleName();
private NetWorkBroadCastReceiver mNetWorkBroadCastReceiver;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(initView());
initData();
}
protected abstract int initView();
protected void initData() {
IntentFilter intentFilter =new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
mNetWorkBroadCastReceiver =new NetWorkBroadCastReceiver(this);
registerReceiver(mNetWorkBroadCastReceiver, intentFilter);
}
@Override
public void onNetWorkChanged(Utils.NetState state) {
Toast.makeText(this, state +"--", Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mNetWorkBroadCastReceiver);
}
}
最后附上demo。谢谢大家阅读