您的位置:首页 > 移动开发 > Android开发

Android中 实现队列方式处理优先级信息

2018-03-03 12:10 417 查看
需求:当界面在处理消息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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: