Android中判斷網路是否連線
阿新 • • 發佈:2018-12-17
//封裝一個判斷網路類 public class HttpNet { public static boolean isNetConnected(Context context) { boolean isNetConnected; // 獲得網路連線服務 ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connManager.getActiveNetworkInfo(); if (info != null && info.isAvailable()) { isNetConnected = true; } else { isNetConnected = false; } return isNetConnected; } }
//有網路時,網上載入資料,沒網時,載入本地的資料 public class Frag21 extends Fragment {
private PullToRefreshListView pulllistview; private int num = 1; private String Url = "http://www.xieast.com/api/news/news.php?page="; private HttpUtils httpUtils; private ArrayList<User.DataBean> list = new ArrayList<>(); //private DbUtils dbUtils; private MyAdapter myAdapter; private DbUtils dbUtils; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_frag21, container, false); //初始化控制元件 pulllistview = view.findViewById(R.id.pulllistview); dbUtils = new DbUtils(getActivity()); //設定模型 pulllistview.setMode(PullToRefreshBase.Mode.BOTH); //設定介面卡 myAdapter = new MyAdapter(getActivity(), list); pulllistview.setAdapter(myAdapter); //設定監聽 pulllistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { Toast.makeText(getActivity(), "fd", Toast.LENGTH_SHORT).show(); list.clear(); getmData(1); } @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) { Toast.makeText(getActivity(), "上拉", Toast.LENGTH_SHORT).show(); num++; getmData(num); } }); getmData(1); return view; } //獲取資料 public void getmData(int num) { boolean flag = new HttpNet().isNetConnected(getActivity()); // Toast.makeText(getActivity(),""+b,Toast.LENGTH_SHORT).show(); if (flag) { //例項化物件 httpUtils = new HttpUtils(); httpUtils.getpath(Url + num); httpUtils.gethttpUtils(new HttpUtils.SetDate() { @Override public void getData(String str) { Gson gson = new Gson(); User user = gson.fromJson(str, User.class); //把資料快取到本地資料庫 dbUtils.insert(str); list.addAll(0, user.getData()); myAdapter.getList(list); pulllistview.onRefreshComplete(); } }); } else { Toast.makeText(getActivity(), "親,沒網啦", Toast.LENGTH_SHORT).show(); String query = dbUtils.query(); Toast.makeText(getActivity(), query.toString(), Toast.LENGTH_SHORT).show(); User userdata = new Gson().fromJson(query, User.class); List<User.DataBean> dataBeanList = userdata.getData(); list.addAll(dataBeanList); myAdapter.getList(list); } }
}