Skip to content Skip to sidebar Skip to footer

Android - Calling Ui Thread From Worker Thread

Hi I want to make Toast available to me no-matter-what and available from any thread whenever I like within my application. So to do this I extended the Activity class: import andr

Solution 1:

What's wrong with runOnUiThread?

http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)

activity.runOnUiThread(new Runnable() {
    publicvoidrun() {
        Toast.makeText(activity, "Hello, world!", Toast.LENGTH_SHORT).show();
    }
});

Solution 2:

use below code. create activity object which contains your activity instance..

activity.runOnUiThread(new Runnable() {
  publicvoidrun() {
    Toast.makeText(activity.getApplicationContext(),"Toast text",Toast.LENGTH_SHORT).show();
  }
);

Solution 3:

This will allow you to display the message without needing to rely on the context to launch the toast, only to reference when displaying the message itself.

runOnUiThread was not working from an OpenGL View thread and this was the solution. Hope it helps.

private Handler handler = new Handler();
handler.post(new Runnable() {
    publicvoidrun() {
        Toast.makeText(activity, "Hello, world!", Toast.LENGTH_SHORT).show();
    }
});

Solution 4:

You can't just cast the result of getThread() to an instance of your MyActivity base class. getThread() returns a Thread which has nothing to do with Activity.

There's no great -- read: clean -- way of doing what you want to do. At some point, your "worker thread" abstraction will have to have a reference to something that can create a Toast for you. Saving off some static variable containing a reference to your Activity subclass simply to be able to shortcut Toast creation is a recipe for memory leaks and pain.

Solution 5:

Why don't you send an intent that is captured by a BroadCastReceiver, then the broadcast receiver can create a notification in the notification tray. It's not a toast, but its a way to inform the user that his post has been successful.

Post a Comment for "Android - Calling Ui Thread From Worker Thread"