Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast created in an IntentService never goes away

Tags:

android

I have an IntentService that downloads some files. The problem is that I create a Toast inside the IntentService like this

Toast.makeText(getApplicationContext(), "some message", Toast.LENGTH_SHORT).show(); 

The Toast will never disappear event if I exit the app. The only way to destroy it is to kill the process.

What am I doing wrong?

like image 782
jax Avatar asked Jul 21 '10 05:07

jax


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

Which method is used to display created toast?

Display the created Toast Message using the show() method of the Toast class. The code to show the Toast message: Toast. makeText(getApplicationContext(), "This a toast message", Toast.

What is toast alert in Android?

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.

What is Android widget toast?

android.widget.Toast. A toast is a view containing a quick little message for the user. The toast class helps you create and show those. When the view is shown to the user, appears as a floating view over the application.


1 Answers

The problem is that IntentService is not running on the main application thread. you need to obtain a Handler for the main thread (in onCreate()) and post the Toast to it as a Runnable.

the following code should do the trick:

@Override public void onCreate() {     super.onCreate();     mHandler = new Handler(); }  @Override protected void onHandleIntent(Intent intent) {     mHandler.post(new Runnable() {                     @Override         public void run() {             Toast.makeText(MyIntentService.this, "Hello Toast!", Toast.LENGTH_LONG).show();                         }     }); } 
like image 115
rony l Avatar answered Oct 29 '22 21:10

rony l