In my app, queued toasts appearing again and again when app goes into background so I did following to solve the problem.
Add code to detect when app goes into background. One way to register life cycle handler. For More detail ref
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
App.inBackground = true;
when app goes to background and show toast using SmartToast class
public class SmartToast {
static ArrayList<WeakReference<Toast>> toasts = new ArrayList<>();
public static void showToast(@NonNull Context context,@NonNull String message){
//this will not allowed to show toast when app in background
if(App.inBackground) return;
Toast toast = Toast.makeText(context,message,Toast.LENGTH_SHORT);
toasts.add(new WeakReference<>(toast));
toast.show();
//clean up WeakReference objects itself
ArrayList<WeakReference<Toast>> nullToasts = new ArrayList<>();
for (WeakReference<Toast> weakToast : toasts) {
if(weakToast.get() == null) nullToasts.add(weakToast);
}
toasts.remove(nullToasts);
}
public static void cancelAll(){
for (WeakReference<Toast> weakToast : toasts) {
if(weakToast.get() != null) weakToast.get().cancel();
}
toasts.clear();
}
}
call SmartToast.cancelAll();
method when app goes into background to hide current and all pending toasts. Code is fun. Enjoy!