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?
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()
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.
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.
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.
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(); } }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With