如何从非 ui Widget 线程发布 toast

2022-01-18 00:00:00 multithreading widget android java

在从小部件中的非 UI 线程调用函数后,我尝试发布祝酒词.我已经阅读了多种执行此操作的方法(发布/新处理程序/广播),但大多数方法似乎针对的是活动而不是小部件类,我无法工作.

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

我知道你不能在小部件中使用 runOnUiThread,但是基本上做我想做的最好的方法是什么???

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

提前致谢

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();
        }
    });


 }

}

推荐答案

您可以创建自己的 runOnUiThread() 版本.当我需要从 Activity 外部在 UI 线程中运行某些东西时,我会使用这种方法:

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

然后,您可以简单地调用 ThreadPool.runOnUiThread(runnable).

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

您可以在此系列文章中找到有关其工作原理的更多信息:Android:Looper、Handler、HandlerThread.第一部分

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

相关文章