需求:当界面在处理消息A时,突然接收到消息B,需要立马显示B的信息,然后再继续显示消息A,或者接收到消息C,再显示完消息A后再显示消息C;
原理很简单 在一个轮询中,查询消息列表中的元素,先处理优先级最高的那一个,之后再处理优先级次高的那一个;
先做一个对象类
private class Obj{
int val;
int times;
public Obj(int val, int times){
this.val = val;
this.times = times;
}
}
再做一个保存消息的列表
List<Obj> mList = new ArrayList<fragment_1.Obj>();
再做一个轮询的机制
private Runnable handlermsg_run = new Runnable() {
@Override
public void run() {
if (mList.size() != 0) {
Obj val = mList.get(0);
int tt = doSomething(val);
state.setText(val.val+" + " + tt);
if (tt == 0) {
mList.remove(0);
tv.setText(getList(mList));
System.out.println("- remove - " + val.val + ">> " + getList(mList));
}
}
han.postDelayed(this, 500);
}
}; han = new Handler(Looper.getMainLooper());
han.post(handlermsg_run);
处理插入列表信息
private void insert(int random) {
int times = 5;
int newValue = random;
synchronized (mList) {
if (mList.size() == 0)
mList.add(new Obj(random, times));
else if (mList.get(0).val != newValue) {
boolean sHas = false;
for (Obj obj : mList) {
if (obj.val == newValue) {
sHas = true;
break;
}
}
if (!sHas) {
mList.add(0, new Obj(newValue, times));
sort(mList);
} }
}
}
对插入的消息进行排序
private static Comparator<? super Obj> comparator = new Comparator<Obj>() { @Override
public int compare(Obj arg0, Obj arg1) {
return arg0.val - arg1.val;
}
}; private static void sort(List<Obj> mList) {
Collections.sort(mList, comparator);
}