Ok, I too am trying to cancel a Toast, and can't seem to get
the cancel() call to get invoked in either the Activity.onDestroy()
or the Activity.onStop(), etc. After some API-doc reading and
googling of others needing help getting Toasts to get cancelled,
I'm thinking I'm still not clear on when Activities get stopped,
paused, destroyed. I need a sure-fire way to force my activity
to get paused or stopped.
In my specific case, since there are only short and long
duration Toasts, I decided to iterate a loop 5 times doing
a show() of a long-duration toast, so it would stay on-screen
for 15-20 seconds. That works fine!
But, the drawback (negative side-effect) of using a Toast object
is that they persist even AFTER the user abandons your app and
goes back to home-screen and starts using some other app...your
toast is gonna live for the next 15-20 seconds, unless you
can guarantee that you can find some place (some way) to
invoke cancel(). Also, you must believe that Android will
honor your call to cancel() !
So, to that end, I've been tweaking my simple loop, trying to
invoke cancels right in the loop, and prove to myself it will
honor a cancel call, and visually behave as expected.
Code snippet:
Note: 'toast' is a public INSTANCE variable, so we
have only ONE instance of the Toast-object [ as is
recommended above, and which a commenter confirmed
was working two years ago, in Activity onStop() and OnDestroy() ]
toast = Toast.makeText(ctxt, result, Toast.LENGTH_LONG);
for (int i=0; i < 5; i++)
{
// Long-toasts each last about 3.5 secs
toast.show();
android.os.SystemClock.sleep(1500);
toast.cancel();
android.os.SystemClock.sleep(1500);
toast = Toast.makeText(ctxt, result, Toast.LENGTH_LONG);
}
Ok, the original loop contained just that one line doing the show.
That works, by itself.
But to experiment, I added those next four lines, to sleep for about
half way thru the 3.5 second showing, then cancel it, sleep again
for a second and a half, and then re-create and show the Toast again.
I expected to see the toast for approx 1.5 secs, then see it disappear,
and come back on in another 1.5 secs, etc.
Guess what...the toast never appears AT ALL!
Ok, I'm in total mumble-mode...what am I missing, in
understanding the inner-mysteries of how the Toast-class
is implemented and is supposed to behave?
And, back to my first issue: How best to get my
Activity to go into a paused or stopped state?
[ Note: I READ this forum a LOT...it's great !!! This is my first posting
into the middle of a thread-discussion...Sorry that my reply
is getting flagged as an ANSWER, rather than as a QUESTION relating
to this thread's topic. ]