How to post toast from non ui Widget thread

我的未来我决定 提交于 2019-12-29 08:23:09

问题


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 seem to be aimed at activities rather than widget classes and I can't get any to work.

I have some basic code below... Can anyone tell me the best way to do what I need to do and maybe provide an example... Thank you (obviously I've taken out all the unnecessary bits...

I know you can't use runOnUiThread in a widget but what is the best way of basically doing what I want???

Thanks in advance

public class MyWidget extends AppWidgetProvider {

@Override
public void onReceive(final Context context, Intent intent) {
    super.onReceive(context, intent);
            new Thread(new Runnable() {
                public void run() {
                        DoStuff();
                }
            }).start();
}

 public void DoStuff () {

      //do a load of stuff on the non UI thread which might take some time and return a string

    String mymessage = "amessage"

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(context, mymessage, Toast.LENGTH_SHORT).show();
        }
    });


 }

}


回答1:


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




回答2:


  • 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.



来源:https://stackoverflow.com/questions/39917308/how-to-post-toast-from-non-ui-widget-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!