Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

java - How to post toast from non ui Widget thread

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


 }

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...