Posting Toast message from a Thread

前端 未结 4 2133
温柔的废话
温柔的废话 2020-12-03 22:09

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 t

相关标签:
4条回答
  • 2020-12-03 22:11

    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.

    0 讨论(0)
  • 2020-12-03 22:11

    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();
        }
    };
    
    0 讨论(0)
  • 2020-12-03 22:27

    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();
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-03 22:30

    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();
    
    0 讨论(0)
提交回复
热议问题