在BaseActivity中,接收网络状态变化广播。使用EventBus进行相应的提示通知。
一、自定义NetBroadcastReceiver网络监听
import org.greenrobot.eventbus.EventBus; /** * Created by zachary on 2020/04/10. * 全局网络状态监听 */ public class NetBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { EventBus.getDefault().post(new MessageEvent("networkChanges", getNetworkConnectionType(context))); } public String getNetworkConnectionType(Context context) { //获取连接管理器 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager == null) return "当前网络已断开"; //获取网络连接信息 NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isAvailable()) { if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { return "当前使用WIFI网络"; } if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { return "当前使用移动数据网络"; } } return "网络已断开"; } }二、集成EventBus并编写消息类
// 事件发布-订阅总线 implementation 'org.greenrobot:eventbus:3.2.0'消息类:
/** * Created by zachary on 2020/04/10. * 网络变化消息类 */ public class MessageEvent { private String type; private String contect; public MessageEvent(String type, String contect) { this.type = type; this.contect = contect; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getContect() { return contect; } public void setContect(String contect) { this.contect = contect; } }三、BaseActivity中,注册广播并接收消息。
/** * Created by zachary on 2020/04/10. * 父Activity */ public abstract class SuperActivity extends RxAppCompatActivity { // 网络广播器 private NetBroadcastReceiver receiver; // 当前网络状态信息 private String strNetInfo = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(getContentViewId()); // 为清除数据做准备 mActivity = this; if (regEvent()) { EventBusUtils.register(this); } // 注解注册 ButterKnife.bind(this); receiver = new NetBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); registerReceiver(receiver, intentFilter); initView(); initData(); } public abstract int getContentViewId(); public abstract void initView(); public abstract void initData(); /** * 需要接收事件 重写该方法 并返回true */ protected boolean regEvent() { return true; } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(MessageEvent event) { if (event.getType().equals("networkChanges")) { // 不为空且与上次记录不同 if (!TextUtil.isEmpty(strNetInfo) && !strNetInfo.equals(event.getContect())) { Toast.makeText(mActivity,event.getContect(),Toast.LENGTH_SHORT).show(); } strNetInfo = event.getContect(); } } @Override protected void onDestroy() { super.onDestroy(); // 解除注解 EventBus.getDefault().unregister(this); // 移除Activity ActivityCollector.removeActivity(this); } }注:每次网络发生变化时:会弹出信息。