How to display a Toast within a Thread on Android?

3

I'm developing an application and I needed to display a Toast at some point inside a Thread, but I'm not getting it, does anyone know how it's possible and if it's possible to do so? Thank you in advance.

Note: if it is not a toast, it could be a Dialog too, but it has the same problem.

    
asked by anonymous 28.10.2015 / 15:19

2 answers

7

The reason is that it is not allowed to access objects that use the UI, such as Toast , a Thread other than UIThread MainThread) .

In the% method of the Thread method, use the run() method to put a Runnable in UIThread .

new Thread() {
    public void run() {

        ....
        ....
        runOnUiThread(new Runnable() {

            @Override
            public void run() {

                //Coloque aqui o código que necessita de correr
                //na UI thread, como por exemplo o Toast
            }
        });

    }
}.start();

Note: The same applies if you have an AsyncTask and if you want to use Toast in runOnUiThread() .

    
28.10.2015 / 15:29
3

I think you need to call Toast.makeTexts from the Thread UI, inside your thread you can do this:

activity.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(activity, "Sou um toast dentro de uma thread", Toast.LENGTH_SHORT).show();
  }
}); 
    
28.10.2015 / 15:28