Android中 實現隊列方式處理優先順序資訊

來源:互聯網
上載者:User

標籤:簡單   資訊   bool   處理   err   als   super   color   插入   

需求:當介面在處理訊息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);    }

 

Android中 實現隊列方式處理優先順序資訊

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.