网络状态变化监听帮助类 NetBroadcastReceiverHelper
public class NetBroadcastReceiverHelper {private static final String TAG = "NetBroadcastReceiverHelper";private static final String NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";private Context mContext;private boolean mIsRegisterReceiver;private NetBroadcastReceiver mNetBroadcastReceiver;private INetBroadcastReceiverListener mListener;public NetBroadcastReceiverHelper(Context context, INetBroadcastReceiverListener listener) {mContext = context;mListener = listener;}public void registerNetBroadcast() {if (null == mContext) {DebugLog.d(TAG, "registerNetBroadcast() context is null");return;}DebugLog.d(TAG, "registerNetBroadcast()");mNetBroadcastReceiver = new NetBroadcastReceiver();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(NET_CHANGE_ACTION);mContext.registerReceiver(mNetBroadcastReceiver, intentFilter);mIsRegisterReceiver = true;}public void unregisterNetBroadcast() {if (!mIsRegisterReceiver) {DebugLog.d(TAG, "unregisterNetBroadcast() is not register receiver, do nothing");return;}DebugLog.d(TAG, "unregisterNetBroadcast()");if (null != mContext&& null != mNetBroadcastReceiver) {mContext.unregisterReceiver(mNetBroadcastReceiver);mIsRegisterReceiver = false;}}private class NetBroadcastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {try {if (NET_CHANGE_ACTION.equals(intent.getAction())) {boolean state = NetWorkUtil.isNetWorking();if (null != mListener) {mListener.onNetChange(state);}}} catch (Exception e) {DebugLog.d(TAG, e.getMessage());}}}public interface INetBroadcastReceiverListener {void onNetChange(boolean isNetWorking);}
}
使用
- 在onCreate方法中 进行注册,实现NetBroadcastReceiverHelper.INetBroadcastReceiverListener 监听
private NetBroadcastReceiverHelper mNetBroadcastReceiverHelper;private void registerNetBroadcast() {mNetBroadcastReceiverHelper = new NetBroadcastReceiverHelper(activity, this);mNetBroadcastReceiverHelper.registerNetBroadcast();}
- 在onDestroy或onDestroyView中进行解注册
if (null != mNetBroadcastReceiverHelper) {mNetBroadcastReceiverHelper.unregisterNetBroadcast();}