how to wait for Android runOnUiThread to be finished?

后端 未结 7 1917
予麋鹿
予麋鹿 2020-12-29 00:58

I have a worker thread that creates a runnable object and calls runOnUiThread on it, because it deals with Views and controls. I\'d like to use the result of the work of the

7条回答
  •  [愿得一人]
    2020-12-29 01:36

    Andrew answer is good, I create a class for easier use.

    Interface implementation :

    /**
     * Events for blocking runnable executing on UI thread
     * 
     * @author 
     *
     */
    public interface BlockingOnUIRunnableListener
    {
    
        /**
         * Code to execute on UI thread
         */
        public void onRunOnUIThread();
    }
    

    Class implementation :

    /**
     * Blocking Runnable executing on UI thread
     * 
     * @author 
     *
     */
    public class BlockingOnUIRunnable
    {
        // Activity
        private Activity activity;
    
        // Event Listener
        private BlockingOnUIRunnableListener listener;
    
        // UI runnable
        private Runnable uiRunnable;
    
    
        /**
         * Class initialization
         * @param activity Activity
         * @param listener Event listener
         */
        public BlockingOnUIRunnable( Activity activity, BlockingOnUIRunnableListener listener )
        {
            this.activity = activity;
            this.listener = listener;
    
            uiRunnable = new Runnable()
            {
                public void run()
                {
                    // Execute custom code
                    if ( BlockingOnUIRunnable.this.listener != null ) BlockingOnUIRunnable.this.listener.onRunOnUIThread();
    
                    synchronized ( this )
                    {
                        this.notify();
                    }
                }
            };
        }
    
    
        /**
         * Start runnable on UI thread and wait until finished
         */
        public void startOnUiAndWait()
        {
            synchronized ( uiRunnable )
            {
                // Execute code on UI thread
                activity.runOnUiThread( uiRunnable );
    
                // Wait until runnable finished
                try
                {
                    uiRunnable.wait();
                }
                catch ( InterruptedException e )
                {
                    e.printStackTrace();
                }
            }
        }
    
    }
    

    Using it :

    // Execute an action from non-gui thread
    BlockingOnUIRunnable actionRunnable = new BlockingOnUIRunnable( yourActivity, new BlockingOnUIRunnableListener()
    {
        public void onRunOnUIThread()
        {
            // Execute your activity code here
        }
    } );
    
    actionRunnable.startOnUiAndWait();
    

提交回复
热议问题