1. Create the netUtils tool class. 2. Customize the broadcast class MyBoastcastRececiver. 3. Customize interface NetEvent. 4. Implement your own interface in the class that you want to listen for network changes. Create a netUtils tool class as follows: 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; }Copy the code
} 2, define MyBoastcastRececiver as follows: 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; }} public interface NetEvent {void onNetChange(int Mobile); } a, let the class to listen on the implementation of the interface NetEvent, and then implement its method; B, register your broadcast as follows: 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, create Connect() in this method; @Override public void onNetChange(int Mobile) { // TODO Auto-generated method stub this.Mobile = Mobile; Connect(); } d, in the Connect (); To judge the type and state of the network they are connected to; Switch (netMobile) {case 1: toast.makeText (getActivity(), “already connected to 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(), “network unavailable “, toast.length_long).show(); isok=true; break; } complete !!!!!!!!! PS: there may be some potential bugs, their own projects can achieve its functions, I am a novice, wrong do not spray!