UI引擎机制系列(一)GLRender线程处理接口设计

来源:互联网 发布:3000元左右手机 知乎 编辑:程序博客网 时间:2024/06/03 17:31

GLSurfaceView的线程队列,有以下缺陷:
1)在GLSurfaceView转入后台,放进此GLSurfaceView消息队列的代码依然会立即执行,但执行时可能生成纹理失败。原因是没有gl环境.

myGLSurfaceView.queueEvent(    new Runnable() {        // This method will be called on the rendering thread:        public void run() {              doSomeThing();        }    });

2)没有去除重复消息的功能。
3)没有实现每帧执行一个消息功能。


设计两个消息处理接口:插入消息队列,插入消息集合。都满足需求一:GL消失停止时,停止运行消息。
1)插入消息队列接口queueEvent(Runnable r)
兼容原GLSurfaceView消息队列,放入此消息队列的消息,在onDraw之前依次全部执行。
使用案例:按键和鼠标事件,放入GLRender线程后,要求顺次全部执行。应该使用此消息队列。
2)插入消息集合接口setEvent(String tag,Runnable r)
满足需求二、三:a.去除重复消息,b.单帧执行。
放入此消息集合的消息,依标签(tag)为身份唯一标示,重复消息仅保留最新,去除旧消息。每次onDraw之前,仅执行一条消息。随机执行,不保证先放入先执行。
使用案例:a.状态栏标示改变事件,当有多条消息时,仅最后一条消息有效,可以使用此消息集合。b.连续生成海报等耗时操作,需要在Render线程,但不希望同一帧内太多任务阻塞GLRender线程。可以使用此消息集合。


消息队列图示:



消息集合图示:




实现代码:

1)定义消息队列、实现插入消息队列:

public class HimalayaView extends GLSurfaceView {…    //仿照原GLSurfaceView写线程队列。    private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();    @Override    public void queueEvent(Runnable r) {        if (r == null) {            throw new IllegalArgumentException("r must not be null");        }        synchronized(HimalayaView.this) {            mEventQueue.add(r);            HimalayaView.this.notifyAll();        }}…}

2)定义消息集合、实现插入消息集合:
public class HimalayaView extends GLSurfaceView {…    //事件Set    private Map<String,Runnable> mEventSet = new HashMap<String,Runnable>();        public void setEvent(String tag,Runnable r) {//如果不需要自建的线程队列,仅仅注释掉此方法。        if (r == null) {            throw new IllegalArgumentException("r must not be null");        }        synchronized(mEventSet) {        mEventSet.put(tag, r);        mEventSet.notifyAll();        }    }…}

3)执行消息队列和消息集合
public class HimalayaRenderer implements GLSurfaceView.Renderer {public void onDrawFrame(final GL10 gl) {…//线程事件队列的逻辑Runnable event = null;while (true) { synchronized (mEventQueue) {           if (! mEventQueue.isEmpty()) {               event = mEventQueue.remove(0);           }else{           break;           } }// end of synchronized(            if (event != null) {                event.run();                event = null;            }   };//线程事件集合synchronized (mEventSet) {        if (! mEventSet.isEmpty()) {        String key = mEventSet.keySet().iterator().next();        event = mEventSet.remove(key);        }else{        //break;        }}// end of synchronized(            if (event != null) {                event.run();                event = null;            }                     //onDrawGL2JNILib.native_gl_render();}}


0 0
原创粉丝点击