I'm trying to "remove" a Toast
when switching from a tab to another one, so assuming pausing the focused tab activity. Basically I could apply the cancel method to a single Toast
object, or assign it to null. This works.
The point is when I use TextView and thread the Toast, then the Toast is still visible even if I stop the thread. I started from this point to thread the Toast and trying to stop it according to this one.
How to stop the thread and remove the toast from the system queue, or is there any better solution to achieve that goal (eg multiple toasts in a single activity, stopping showing toasts when swapping from an activity to another one) ?
Calling a Toast (this is Ok):
private void showSingleToast(String toastText, int color, long duration_ms) {
if (mySingleToast instanceof Toast) {
mySingleToast.setText(toastText);
if (null != toastView)
if (toastView instanceof TextView)
toastView.setTextColor(color);
ToastExpander.showFor(mySingleToast, duration_ms);
}
}
Threading the Toast.show()
public class ToastExpander extends Thread {
public static final String TAG = "ToastExpander";
static Thread t;// = null;
// Must be volatile:
static volatile boolean stopFlag = false;
static long scan_freq = 300;
public static void showFor(final Toast aToast, final long durationInMilliseconds) {
aToast.setDuration(Toast.LENGTH_SHORT);
t = new Thread() {
long timeElapsed = 0l;
public void run() {
try {
while (timeElapsed <= durationInMilliseconds || !stopFlag) {
long start = System.currentTimeMillis();
aToast.show();
sleep(scan_freq);
timeElapsed += System.currentTimeMillis() - start;
}
// doesn't work: aToast.cancel();
} catch (InterruptedException e) {
Log.e(TAG, e.toString());
}
} /* end of "run" */
}; /* end of Thread */
t.start();
} /* end showFor */
public static void cancel() {
stopFlag = true;
}
}
Trying to "remove" the Toast (does not work)
private void hideSingleToast() {
//hideTextView(toastView);
toastView = null;
ToastExpander.cancel();
mySingleToast.cancel();
//mySingleToast= null;
}