Android using a view handler to run code

I saw that in AOSP there is a lot of code running something like:

v.post(new Runnable() {
        @Override
        public void run() {
            // Here comes code
            x += y;
        }
    });

      

What's the advantage of making it simple, just doing it x += y;

?

+3


source to share


1 answer


This launch will be called when the view is connected to the main UI thread. look at the post method in the View class.



 /**
     * <p>Causes the Runnable to be added to the message queue.
     * The runnable will be run on the user interface thread.</p>
     *
     * @param action The Runnable that will be executed.
     *
     * @return Returns true if the Runnable was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     *
     * @see #postDelayed
     * @see #removeCallbacks
     */
    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }

        // Postpone the runnable until we know on which thread it needs to run.
        // Assume that the runnable will be successfully placed after attach.
        getRunQueue().post(action);
        return true;
    }

      

0


source







All Articles