Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show toast message from background thread

Tags:

java

android

Consider the following code. In Service.onStart() method i have created and started a thread that should show Toast message but it is not working!

public class MyService extends Service{

    private static final String TAG = "MyService";  
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;    
    }       

    @Override   
    public void onCreate()
    {   
    Toast.makeText(this, "My Service Created", Toast.LENGTH_SHORT).show();
         }  
    @Override
    public void onDestroy() 
    {   
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_SHORT).show();  
    }   
    @Override
    public void onStart(Intent intent, int startid)
    {
      Toast.makeText(this, "My Service Started", Toast.LENGTH_SHORT).show();
      DBIteratorThread dbThread=new DBIteratorThread();
      dbThread.myService=this;
      Thread t1 = new Thread(dbThread);
           t1.start();
    }

}
class DBIteratorThread  implements Runnable
{

    MyService myService;

    public void run()
    {
    //  Toast.makeText(myService, "Thread is Running", Toast.LENGTH_SHORT).show();
            }
}
like image 961
Asif Rafiq Avatar asked Sep 11 '11 14:09

Asif Rafiq


People also ask

Can I show toast from background thread?

Steps: declare a handler in the main activity (onCreate) now create a thread from the main activity and pass the Context of that activity. now use this context in the Toast, instead of using getApplicationContext()

How do you show toast in thread?

myActivity. runOnUiThread(new Runnable() { public void run() { Toast. makeText(myActivity, "Toast Message Text!", Toast.

Which method used for show a text on toast?

Use the makeText() method, which takes the following parameters: The application Context . The text that should appear to the user. The duration that the toast should remain on the screen.

How do I get rid of toast message?

call SmartToast. cancelAll(); method when app goes into background to hide current and all pending toasts.


1 Answers

Do UI stuffs in main/UI thread. Try this:

Handler handler = new Handler(Looper.getMainLooper());

handler.post(new Runnable() {

        @Override
        public void run() {
            //Your UI code here
        }
    });
like image 92
Matheus Henrique da Silva Avatar answered Oct 05 '22 20:10

Matheus Henrique da Silva