开发者

Passing data from bg thread to UI thread using Handler?

In Handler, we can pass some data from a background thread to the UI thread like this:

private void someBackgroundThreadOperation() {
    final String data = "hello";
    handler.post(new Runnable() {
        public void run() {
            Log.d(TAG, "Message from bg thread: " + data);
        } 
    }
}

If we use the above, we cannot then use Handler.removeCallbacks(Runnable r), because we won't have references to any of the anonymous runnables we created above.

We could create a single Runnable instance, and post that to the handler, but it won't allow us to pass any data through:

private void someBackgroundThreadOperation() {
    String data = "hello";
    handler.post(mRunnable); // can't pass 'data' through.
}

private Runnable mRunnable = new Runnable() {
    public void run() {
        Log.d(TAG, "What data?");
    }
}

We can however use the Handler.removeCallbacks(mRunnable) method then, since we have a reference to it.

I know I can setup some synchronization myself to get the second method working, but I'm wondering if Handler offers any utility for passing data through to a single referenced Runnable, almost like in the example above?

The closest I can think of from browsing the docs is to use something like:

private void someUiThreadSetup() {
    mHandler = new Handler(new Callback() {
        @Override
        public boolean handleMessage(Message msg) {
    开发者_C百科        String data = (String)msg.obj;
            return false;
        }
    });
}

private void someBackgroundThreadOperation() {
    String data = "please work";
    Message msg = mHandler.obtain(0, data);
    mHandler.sendMessage(msg);
}

private void cleanup() { 
    mHandler.removeMessages(0);
}

Is this the proper way of doing it?

Thanks


IMHO, the pattern you seek is packaged as the AsyncTask class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜