直接看效果:
实现了有网和没网两种状态的试试广播监听
实现步骤:
1、定义广播接收器
/**
* 监控网络变化
*/
public class NetworkConnectChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean isConnected = NetUtils.isConnected(context);
if (isConnected) {
if (!NetUtils.isNetworkAvailable) {
NetUtils.isNetworkAvailable = true;
//post(Object event)参数是自定义的,接收的地方也是对应自定义的
EventBus.getDefault().post(new NetworkChangeEvent(isConnected));
Log.d("BroadcastReceiver", isConnected + "");
}
} else {
if (NetUtils.isNetworkAvailable) {
NetUtils.isNetworkAvailable = false;
EventBus.getDefault().post(new NetworkChangeEvent(isConnected));
Log.d("BroadcastReceivers", isConnected + "");
}
}
}
}
2、定义事件
public class NetworkChangeEvent {
public boolean isConnected;//是否存在网络
public NetworkChangeEvent(boolean isConnected) {
this.isConnected = isConnected;
}
}
3、判断是否联网方法
public class NetUtils {
public static boolean isNetworkAvailable = false;//标识变量,表示当前网络是否连接
/**
* 判断网络是否连接
* @param context
* @return
*/
public static boolean isConnected(Context context) {
//
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != connectivity) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (null != info && info.isConnected()) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
}
4、BaseActivity中注册广播
NetworkConnectChangedReceiver networkConnectChangedReceiver;
private void initBroadcastReceiver() {
networkConnectChangedReceiver=new NetworkConnectChangedReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
intentFilter.addAction("android.Net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE" );
this.registerReceiver(networkConnectChangedReceiver, intentFilter);
}
5、BaseActivity中处理网络变化时UI的变化
/**
* <基础activity>
*
*/
public abstract class BaseActivity extends AppCompatActivity implements CreateInit, PublishActivityCallBack, PresentationLayerFunc, IMvpView, OnClickListener {
private PresentationLayerFuncHelper presentationLayerFuncHelper;
public BasePresenter presenter;
View mTipView;
WindowManager mWindowManager;
WindowManager.LayoutParams mLayoutParams;
public final String TAG = this.getClass().getSimpleName();
protected boolean mCheckNetWork = true; //默认检查网络状态
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presentationLayerFuncHelper = new PresentationLayerFuncHelper(this);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
setContentView( getLayoutId());
initViews();
initListeners();
initData();
EBApplication.ebApplication.addActivity(this);
//初始化网络提示View
initTipView();
EventBus.getDefault().register(this);
initBroadcastReceiver();
}
NetworkConnectChangedReceiver networkConnectChangedReceiver;
private void initBroadcastReceiver() {
networkConnectChangedReceiver=new NetworkConnectChangedReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
intentFilter.addAction("android.Net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE" );
this.registerReceiver(networkConnectChangedReceiver, intentFilter);
}
private View viewWait;
public void createDialog() {
if (null == viewWait) {
LayoutInflater mInflater = LayoutInflater.from(this);
viewWait = mInflater.inflate(R.layout.wait_dialog, null, false);
this.addContentView(viewWait, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
viewWait.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// removeDialog();
}
});
} else {
viewWait.setVisibility(View.VISIBLE);
}
}
@Override
public void onSuccessWithFlag(T t, int flag) {
JsonObject jsonObject = (JsonObject) t;
if (jsonObject.get("code").getAsString().equals("9000")) {
SharedPreferenceUtil.setInfoToShared(Constants.USER_INFO_KEY,"");
Constants.token= "";
startActivity(new Intent(this,StartActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
}
public void removeDialog() {
if (null != viewWait) {
viewWait.setVisibility(View.GONE);
}
}
private View viewNodata;
public void createNodataDialog() {
if (null == viewNodata) {
LayoutInflater mInflater = LayoutInflater.from(this);
viewNodata = mInflater.inflate(R.layout.nodata_dialog, null, false);
this.addContentView(viewNodata, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
viewNodata.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
removeNodataDialog();
}
});
} else {
viewNodata.setVisibility(View.VISIBLE);
}
}
public void removeNodataDialog() {
if (null != viewNodata) {
viewNodata.setVisibility(View.GONE);
}
}
@Override
public void showLoading() {
createDialog();
}
@Override
public void hideLoading() {
removeDialog();
}
@Override
protected void onResume() {
EBApplication.ebApplication.currentActivityName = this.getClass().getName();
super.onResume();
hasNetWork(NetUtils.isConnected(this));
}
// public abstract void reConnect();
private void hasNetWork(boolean has) {
if (isCheckNetWork()) {
if (has) {
if (mTipView != null && mTipView.getParent() != null) {
mWindowManager.removeView(mTipView);
// reConnect();
}
} else {
if (mTipView.getParent() == null) {
mWindowManager.addView(mTipView, mLayoutParams);
}
}
}
}
public void setCheckNetWork(boolean checkNetWork) {
mCheckNetWork = checkNetWork;
}
public boolean isCheckNetWork() {
return mCheckNetWork;
}
private void initTipView() {
LayoutInflater inflater = getLayoutInflater();
mTipView = inflater.inflate(R.layout.layout_network_tip, null); //提示View布局
mWindowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT);
//使用非CENTER时,可以通过设置XY的值来改变View的位置
mLayoutParams.gravity = Gravity.TOP;
mLayoutParams.x = 0;
mLayoutParams.y = 0;
}
@Override
public void startActivity(Class> openClass, Bundle bundle) {
Intent intent = new Intent(this, openClass);
if (null != bundle)
intent.putExtras(bundle);
startActivity(intent);
}
@Override
public void openActivityForResult(Class> openClass, int requestCode, Bundle bundle) {
Intent intent = new Intent(this, openClass);
if (null != bundle)
intent.putExtras(bundle);
startActivityForResult(intent, requestCode);
}
@Override
public void setResultOk(Bundle bundle) {
Intent intent = new Intent();
if (bundle != null) ;
intent.putExtras(bundle);
setResult(RESULT_OK, intent);
finish();
}
@Override
public void showToast(String msg) {
presentationLayerFuncHelper.showToast(msg);
}
@Override
public void showProgressDialog() {
presentationLayerFuncHelper.showProgressDialog();
}
@Override
public void hideProgressDialog() {
presentationLayerFuncHelper.hideProgressDialog();
}
@Override
public void showSoftKeyboard(View focusView) {
presentationLayerFuncHelper.showSoftKeyboard(focusView);
}
@Override
public void hideSoftKeyboard() {
presentationLayerFuncHelper.hideSoftKeyboard();
}
@Override
protected void onDestroy() {
EBApplication.ebApplication.deleteActivity(this);
if (presenter != null) {
presenter.detachView(this);
}
super.onDestroy();
EventBus.getDefault().unregister(this);
this.unregisterReceiver(networkConnectChangedReceiver);
}
@Override
public void finish() {
super.finish();
//当提示View被动态添加后直接关闭页面会导致该View内存溢出,所以需要在finish时移除
if (mTipView!=null&&mTipView.getParent()!=null){
mWindowManager.removeView(mTipView);
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onNetChangeEvent(NetworkChangeEvent networkChangeEvent){
hasNetWork(networkChangeEvent.isConnected);
}
}
结束
所有Activity都继承BaseActivity,如果某个页面不需要网络状态提示,可以在该页面 onCreate 方法中调用 setCheckNetWork(false)
即可。
所有页面在网络链接恢复后应该可以自动重新发起网络请求,实现原理其实也很简单,在BaseActivity中增加一个reConnect()
的方法,在网络恢复去除提示View的时候调用。在各个页面中重写该方法即可。