Posting Toast message from a Thread

£可爱£侵袭症+ 提交于 2019-11-26 17:15:07

问题


My application launches a thread to query the web for some data. I want to display a Toast message when nothing is found, but my application always crashes.

I've tried using the application Context from within the thread, like so:

Toast.makeText(getApplicationContext(), "testttt", Toast.LENGTH_LONG).show();

I've also tried creating a Runnable with the Toast call and calling runOnUiThread(runnable) from the Thread (the Toast call in this runnable uses the Activity as the first parameter).

Does anyone have any ideas on how to accomplish this?


回答1:


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



回答2:


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



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/4209814/posting-toast-message-from-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!