Android - Calling Ui Thread From Worker Thread
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"