Nella mia app, i toasts in coda vengono visualizzati più e più volte quando l'app passa in background, quindi ho seguito per risolvere il problema.
Aggiungi codice per rilevare quando l'app entra in background. Un modo per registrare il gestore del ciclo di vita. Per maggiori dettagli ref
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
App.inBackground = true;
quando applicazione va a sfondo e mostrare brindisi con classe SmartToast
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();
}
}
chiamata SmartToast.cancelAll();
metodo quando un'applicazione passa in fondo per nascondere brindisi in sospeso in corso e tutti. Il codice è divertente. Godere!
+1 mi ha preso per 4 secondi;) –