Passing data from bg thread to UI thread using Handler?
<p>In Handler, we can pass some data from a background thread to the UI thread like this:</p>

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

<p>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.</p>

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

<pre><code>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?");
    }
}
</code></pre>

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

<p>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?</p>

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

<pre><code>private void someUiThreadSetup() {
    mHandler = new Handler(new Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            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);
}
</code></pre>

<p>Is this the proper way of doing it?</p>

<p>Thanks</p>
