1. 进入页面先访问网络状态.返回true或false表示网络状态的有无,将这个值使用EventBus传给Fragment页面
首先需要导入依赖
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">uses-permission> <uses-permission android:name="android.permission.INTERNET">uses-permission>
3. 某个Activity里面先调用访问网络状态的方法
//进入页面判断网络,发送EventBus黏性事件判断网络状态 boolean flag = NetConnectionUtil.isNetConnectioned(this); if (flag){ //有网状态下 flag = true EventBus.getDefault().postSticky("true"); }else { //无网状态下 flag = false EventBus.getDefault().postSticky("false"); }
4. 判断网络状态,设置网络的封装工具类方法
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.provider.Settings; /** * 判断网络连接的工具类 */ public class NetConnectionUtil { /** * 判断是否有网络连接的方法 */ public static boolean isNetConnectioned(Context context){ boolean flag = false; //1. 获取网络连接对象 ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //2. 获取NetworkInfo对象,获取网络连接的信息,添加权限:NetworkInfo info = manager.getActiveNetworkInfo(); //3. 信息不为空时,就代表网络可用 if (info != null){ return info.isAvailable(); } return flag; } /** * 网络无连接时跳转页面,弹出对话框进行网络的设置 */ public static void setNetConnectionWork(final Context context){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("网络加载错误!"); builder.setMessage("网络连接不可用,是否设置网络?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //跳转到系统的设置网络的界面 Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS); context.startActivity(intent); } }); builder.setNegativeButton("取消",null); builder.show(); } }
5. Fragment里面需要注册 Eventbus,定义一个接受的事件,上面加注解,在销毁的时候取消注册
//初始化EventBus,注册EventBus EventBus.getDefault().register(this);
//在UI主线程,注册粘性订阅事件,进行黏性事件处理函数 @Subscribe(sticky = true,threadMode = ThreadMode.MAIN) //判断网络,请求网络数据 public void getEventBus(String flag){ if (flag.equals("true")){ Toast.makeText(getActivity(),"网络状态良好,访问网络数据正常",Toast.LENGTH_SHORT).show(); //动态传值替换请求路径:get请求方式 presenter.get(num,page); //无动态传值请求路径:get请求方式 //presenter.get(); }else { NetConnectionUtil.setNetConnectionWork(getActivity()); } }
//在onDestory()方法中取消订阅:防止内存溢出 @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().removeAllStickyEvents(); EventBus.getDefault().unregister(this); }