Search code examples
androidandroid-toast

How to cancel all Toasts when app is in background?


I'm using Toasts in my app to display errors from API/local errors to user. But it is annoying if user is in background and Toast message is displayed over his Messenger app (for example) that some request failed. Is there any way how to disable all displayed toasts immediately when App is in background?

All toasts are created in one function for entire App which is inside my Application class.


Solution

  • Set a variable in your MasterActivity (if you have one, or set in your MainActivity) like this:

      public static boolean IS_IN_FOREGROUND = false;
    

    and set it in your lifecycle like this:

      @Override
      protected void onResume() {
        super.onResume();
        IS_IN_FOREGROUND = true;
      }
    
      @Override
      protected void onPause() {
        super.onPause();
        IS_IN_FOREGROUND = false;
      }
    

    then check it before calling your toast method.