Question

If I issue a toast when my App's activity is not in the foreground then the toast will still show up on the screen. How can I prevent my toast from showing up when my app is running in the background. i.e with none of its activities currently the activity being shown.

I am thinking that I must somehow detect that my activities are not the activity currently being shown and when true not issue any toasts; but how would I detect this condition?

Thanks

Was it helpful?

Solution

Set a flag when your app is in the background (i.e. in onPause), and don't send out toasts if the flag is set.

If you have tons of activities, you can define your own Activity base class that wraps this functionality.

OTHER TIPS

Have you tried setting a variable or some indicator when the onPause() method is called for that activity to denote its been put into the background, then turn that indicator off when onResume() is called?

Then let that toast occur if the indicator is off.

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top