最近做项目,遇到3W多条记录一次需要全部请求下来到移动端,处理方法:
一、采用内存数据库保存记录。
二、请求时采用重新开新线程方式,在子线程中请求网络请求。
三、数据请求后,可通过EventBus来设置返回结果的参数和返回信息,若其它类需要获取状态时,需要自己注册监听,动态去获取返回值。
参考:https://blog.csdn.net/newactivity/article/details/90717940
使用场景:应用程序内各组件间、组件与后台线程间的通信。
比如请求网络,等网络返回时通过Handler或Broadcast通知UI,两个Fragment之间需要通过Listener通信,这些需求都可以通过EventBus实现。
使用步骤:
1. 添加依赖:implementation 'org.greenrobot:eventbus:3.0.0'
2. 注册:EventBus.getDefault().register(this);
3.构造消息发送类(post调用的对象)
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
4.发布消息
EventBus.getDefault().post(new Student("刘哈哈", 27));
5.接收消息:可以有四种线程模型选择
//接收事件
@Subscribe(threadMode = ThreadMode.MAIN)
public void studentEventBus(Student student){
mShow.setText("姓名:"+student.getName()+" "+"年龄:"+student.getAge());
}
6.解注册(防止内存泄漏):EventBus.getDefault().unregister(this);
四、网络请求成功后,需要注意文件流的大小,太大容易下载缓慢,解决缓慢问题
1、JSON返回格式,尽量去KEY,将JSONOBJECT修改为JSONArray格式。
2、对数据进行压缩,采用GZIP对数据进行压缩处理:网络请求时服务器对数据压缩,移动端请求到结果后,再进行解压。