如何从非 ui 窗口小部件线程 post toast

How to post toast from non ui Widget thread

我正在尝试 post 从小部件中的非 UI 线程调用函数后干杯。我已经阅读了多种执行此操作的方法 (post/new handler/broadcast),但大多数方法似乎都是针对活动而不是小部件 类,而且我无法使用任何方法。

我在下面有一些基本代码...任何人都可以告诉我做我需要做的事情的最佳方法并可能提供一个示例...谢谢(显然我已经删除了所有不必要的部分。 ..

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

提前致谢

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


 }

}

您可以创建自己的 运行OnUiThread() 版本。当我需要从 Activity:

之外的 UI 线程中 运行 某些内容时,这就是我使用的方法
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)

您可以在这个 post 系列中找到有关其工作原理的更多信息:Android: Looper, Handler, HandlerThread. Part I

  • 您应该使用 asyncTask 在后台执行操作而不是 使用 Thread().
  • 如果你只想要一个简单的吐司,请删除 Thread() 并吐司 留言。
  • 如果你还需要用到线程又想显示message.You可以 使用以下内容的敬酒消息:

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

不建议使用looper