Want to hide Android toast when the app is in the background

If I issue a toast when the application’s activity is not in the foreground, a toast will still be displayed on the screen. How can I prevent my toast from showing when my app is running in the background. those. none of his activities are currently shown.

I think I should somehow find out that my actions are not the activities that are currently being shown, and when the truth does not issue any toasts; but how would I detect this condition?

thanks

+6
android toast
source share
3 answers

Set the flag when your application is in the background (i.e. in onPause ), and do not send toasts if the flag is set.

If you have a lot of actions, you can define your own base Activity class that wraps this functionality.

+9
source share

Have you tried to set a variable or some indicator when the onPause() method is called for this action to indicate it is placed in the background, then turn off this indicator when onResume() is onResume() ?

Then let this toast happen if the indicator is off.

+2
source share

In my application, the next toast appears again and again when the application goes into the background, so I did the following to solve the problem.

Add code to detect when the application goes into the background. One way to register a lifecycle handler. Read more ... ref

 registerActivityLifecycleCallbacks(new MyLifecycleHandler()); 

App.inBackground = true; when the app goes into the background and shows a toast using the 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 the SmartToast.cancelAll(); method SmartToast.cancelAll(); when the app goes into the background to hide the current and all pending toasts. Code is fun. Enjoy it!

0
source share

All Articles