How to post toast from non ui Widget thread

后端 未结 2 866
故里飘歌
故里飘歌 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

    0 讨论(0)
  • 2020-12-20 09:20
    • You should use asyncTask for do the things in background instead of using Thread().
    • And if you just want a simple toast remove Thread() and toast the message.
    • If you still need to use thread and want to display message.You can toast message using below:

    if(Looper.myLooper() == null) {

        Looper.getMainLooper();
    

    }

    Looper.prepare();

    new Handler().post(new Runnable() {

        @Override
        public void run() {
    
            Toast.makeText(LargeAppWidget.this.context, "Sample Text", Toast.LENGTH_SHORT).show();
    
        }
    });
    
    Looper.loop();
    

    It is not recommended to use looper.

    0 讨论(0)
提交回复
热议问题