网络监听和数据缓存结合使用:解决打开app数据加载时界面空白的问题
程序员文章站
2024-03-24 16:01:34
...
网络监听和数据缓存结合使用:解决打开app数据加载时界面空白的问题
一、网络监听
1.写成抽象类和方法:
/**
* 网络监听
*/
public abstract class NetMonitorBaseFragment extends BaseFragment {
//网络连接监听
private IntentFilter intentFilter;
private NetworkChangReceiver networkChangReceiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); //广播接收器想要监听什么广播,就在这里添加相应的action
networkChangReceiver = new NetworkChangReceiver();
getActivity().registerReceiver(networkChangReceiver, intentFilter);//调用resigerReceiver()方法进行注册
}
//广播监听网络变化
class NetworkChangReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);//得到系统服务类
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {//网络连接
onNetworkConnected();
} else {
onNetworkDisConnected();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
getActivity().unregisterReceiver(networkChangReceiver);
}
/**
* 网络连接状态
*/
protected abstract void onNetworkConnected();
/**
* 网络断开的时候调用
*/
protected abstract void onNetworkDisConnected();
}
2.继承抽象类并实现抽象方法:
//连接网络
@Override
protected void onNetworkConnected() {
}
//断开网络
@Override
protected void onNetworkDisConnected() {
}
二、数据缓存
1.缓存方式:
private ACache mCache;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_home, container, false);
mCache = ACache.get(getActivity());
return view;
}
/**
* listView加载数据
*/
private void initListView() {
server.getListImg(new CallBack() {
@Override
public void onResponse(String response) {
ImgInfoList img = gson.fromJson(response, ImgInfoList.class);
if (img.getRESULTCODE().getVIPCODE() == 0) {
if (img.getVIPCONTENT().size() > 0) {
listList = img.getVIPCONTE
mCache.put("ListImage", gson.toJson(listList));//缓存数据
}
refreshLoad.stopRefresh();//停止刷新
listViewAdapter.setList(listList);
} else {
refreshLoad.stopRefresh();//停止刷新
ToastXutil.showToast(getActivity(), img.getRESULTCODE().getVIPINFO());
}
}
});
}
三、网络监听和数据缓存结合使用
四、效果展示
上一篇: 递推专题