如何从非ui Widget线程发布吐司 [英] How to post toast from non ui Widget thread
问题描述
我试图在窗口小部件中的非UI线程调用函数后发布一个toast。我已经阅读了多种方法(post / new handler / broadcast),但大多数方法似乎都是针对活动而不是widget类,我无法工作。
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()版本。这是我在需要从活动外部在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
这篇关于如何从非ui Widget线程发布吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!