Posting Toast message from a Thread

萝らか妹 提交于 2019-11-27 15:32:07

Try to post inside to a Handler object.

final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
    public void run() {
        Toast(this, message, duration).show();
    }

new Thread() {
    public void run() {
        mHandler.post(mUpdateResults);
    }
}.start();

Toast.makeText().show() definitely needs to be run on the UI thread.

You should probably use an AsyncTask like Octavian Damiean mentioned, but here's some code using runOnUiThread if you're set on using that:

    public void showToastFromBackground(final String message) {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        }
    });
}

Try implementing a class extending "Handler" in your Activity class and send a Message to it from the other thread. Explained more in detail here:

http://www.anddev.org/the_pizza_timer_-_threading-drawing_on_canvas-t126.html

And please, when asking a question like this, include the stack trace you are getting.

If you're running the Handler from your Activity class, you can set the context by just referencing the .this of your Activity like so:

final Runnable showToastMessage = new Runnable() {
    public void run() {
        Toast.makeText(YourActivity.this, "Message", Toast.LENGTH_SHORT).show();
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!