How to post toast from non ui Widget thread

后端 未结 2 873
故里飘歌
故里飘歌 2020-12-20 08:31

I am trying to post a toast after calling a function from a non UI thread in a widget. I\'ve read multiple ways of doing this (post/new handler/broadcast) but most methods s

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 09:13

    You can create your own version of runOnUiThread(). This is what I use when I need to run something in the UI thread from outside an Activity:

    public final class ThreadPool {
        private static Handler sUiThreadHandler;
    
        private ThreadPool() {
        }
    
        /**
         * Run the {@code Runnable} on the UI main thread.
         *
         * @param runnable the runnable
         */
        public static void runOnUiThread(Runnable runnable) {
            if (sUiThreadHandler == null) {
                sUiThreadHandler = new Handler(Looper.getMainLooper());
            }
            sUiThreadHandler.post(runnable);
        }
    
        // Other, unrelated methods...
    }
    

    Then, you can simply call ThreadPool.runOnUiThread(runnable).

    You can find more information on how this works in this post series: Android: Looper, Handler, HandlerThread. Part I

提交回复
热议问题