欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

判断网络

程序员文章站 2022-03-04 08:48:20
...
判断有没有网络

if判断没有网络进行吐司


 if(!HaveNetWork()) {
            Toast.makeText(getActivity(), "没有网络", Toast.LENGTH_SHORT).show();
     }else{

	//另一种情况就是有网进行请求数据

            String Urlwith = path +page;
            new AsyncTask<String,String, List<com.example.moni.bean.Person.DateBean>>(){

                @Override
                protected List<com.example.moni.bean.Person.DateBean> doInBackground(String... strings) {
                    com.example.moni.bean.Person dian = null;

                    try {
                        URL url = new URL(path);

                        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                        httpURLConnection.setReadTimeout(5000);
                        httpURLConnection.setConnectTimeout(5000);
                        httpURLConnection.setRequestMethod("GET");

                        int request = httpURLConnection.getResponseCode();
                        if(request == 200){
                            String str = String2(httpURLConnection.getInputStream());
                            dian =  new Gson().fromJson(str, com.example.moni.bean.Person.class);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return dian == null ? null : dian.getData();
                }

                @Override
                protected void onPostExecute(List<com.example.moni.bean.Person.DateBean> dateBean) {
                    if(dateBean == null){
                        Toast.makeText(getActivity(),"下拉数据失败",Toast.LENGTH_SHORT).show();
                    }
                    updateset(dateBean);
                    stopdf();

                    super.onPostExecute(dateBean);
                }
            }.execute(Urlwith);
        }

创建一个方法
//判断网络
public boolean HaveNetWork() {
ConnectivityManager con = (ConnectivityManager) getActivity().getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo act = con.getActiveNetworkInfo();
return act!=null && act.isAvailable();
}