一,准备: 1,创建netUtils工具类。 2,自定义广播类MyBoastcastRececiver。 3,自定义接口NetEvent。 4,在自己要监听网络变化的类中,去实现自己定义的接口。 二,具体步骤: 1,创建netUtils工具类如下: public class NetUtil { private static final int NETWORK_MOBILE = 0; private static final int NETWORK_WIFI = 1; private static final int NETWORK_NONE = -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;
}
复制代码
} 2,自定义广播类MyBoastcastRececiver如下: public class MyBoastcastRececiver extends BroadcastReceiver{ private NetEvent netEvent; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { int netWrokState = NetUtil.getNetWorkState(context); if (netEvent != null){ netEvent.onNetChange(netWrokState); }
} } public void setNetEvent(NetEvent netEvent) { this.netEvent = netEvent; } }
3,自定义接口NetEvent如下: public interface NetEvent { void onNetChange(int Mobile); } 4,在自己要监听网络变化的类中,去实现自己定义的接口如下: a,让要监听的类实现接口NetEvent,然后实现其方法; b,先动态注册你的广播如下: private int netMobile; private MyReceiver myReceiver; private boolean neta; @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); if (myReceiver == null) { myReceiver=new MyReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); getActivity().registerReceiver(myReceiver, filter); myReceiver.setNetEvent(this); } } c,在此方法中创建Connect(); @Override public void onNetChange(int Mobile) { // TODO Auto-generated method stub this.Mobile = Mobile; Connect(); } d,在Connect();中去判断自己连接网络的类型以及状态; switch (netMobile) { case 1: Toast.makeText(getActivity(), "已连上wifi", Toast.LENGTH_LONG).show(); if(isok){ initData(); notifyDataSetChanged(); } break; case 0: Toast.makeText(getActivity(), "已连上移动网络", Toast.LENGTH_LONG).show(); if(isok){ initData(); Adapter.notifyDataSetChanged(); } break; case -1: Toast.makeText(getActivity(), "网络不可用", Toast.LENGTH_LONG).show(); isok=true; break; } 完成!!!!!!!!! PS:可能还存在一些潜在的bug,自己的项目可以实现其功能,我是一个新手,错了勿喷!