HandlerThread

来自个人维基
跳转至: 导航搜索

这个类可以创建一个包含有Looper的Thread,而后则可将其中的Looper对象用来作为参数创建Handler,如此则可在一个独立的thread中处理其他进程添加的消息,实现异步处理。

  • ps, 此类已经完美处理了线程间的同步问题,从而确保了在创建Handler时looper已经创建,是有效的

使用示例:

    public CarouselViewHelper(Context context) {
        ...
        mHandlerThread = new HandlerThread(TAG + ".handler");
        mHandlerThread.start();

        mAsyncHandler = new AsyncHandler(mHandlerThread.getLooper());
        ...
    }  

    class AsyncHandler extends Handler {
        AsyncHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            int id = msg.arg1;
            if (id >= mCarouselView.getCardCount()) {
                Log.e(TAG, "Index out of range for get, card:" + id);
                return;
            }
            if (msg.what < REQUEST_TEXTURE_N || msg.what > REQUEST_END) {
                Log.e(TAG, "Unknown message: " + id);
                return;
            }
            if (msg.what < REQUEST_DETAIL_TEXTURE_N) {
                // REQUEST_TEXTURE_N
                final Bitmap bitmap = getTexture(id);
                if (bitmap != null) {
                    mSyncHandler.obtainMessage(SET_TEXTURE_N, id, 0, bitmap).sendToTarget();
                }

                TextureParameters params = getTextureParameters(id);
                if (params != null) {
                    mSyncHandler.obtainMessage(SET_MATRIX_N, id, 0,
                            params.matrix.getArray()).sendToTarget();
                }
            } else if (msg.what < REQUEST_GEOMETRY_N) {
                // REQUEST_DETAIL_TEXTURE_N
                final Bitmap bitmap = getDetailTexture(id);
                if (bitmap != null) {
                    mSyncHandler.obtainMessage(SET_DETAIL_TEXTURE_N, id, 0, bitmap).sendToTarget();
                }
            } else if (msg.what < REQUEST_END) {
                // REQUEST_GEOMETRY_N
                Mesh mesh = getGeometry(id);
                if (mesh != null) {
                    mSyncHandler.obtainMessage(SET_GEOMETRY_N, id, 0, mesh).sendToTarget();
                }
            }
        }
    };