0

I have created an xamarin android app incorporating toast popups that display when users lose, then regain internet connection in my app.

These toasts appear correctly but when I my app is in the background i still get the toasts displaying when i lose/regain internet connection displaying even over other apps that are in the foreground.

I have tried to use a global instance of the toast class then call toast.cancel() on onstop and onpause events, code below. Any ideas?

//my global toast class
Toast toast;

//create a toast message and display
if (toast != null) { toast.Cancel(); }
toast = Toast.MakeText(Application.Context, "You are Offline.", ToastLength.Long).show();

protected override void OnStop()
{
      base.OnStop();
      if (toast != null) toast.Cancel();
}

protected override void OnPause()
{
    base.OnPause();
    if (toast != null) toast.Cancel();
}
pinman
  • 93
  • 1
  • 3
  • 13

2 Answers2

0

The below code worked fine for me. The trick is to keep track of the last Toast that was shown, and to cancel that one correctly.

Refer below link for an exact scenario like yours.

Android cancel Toast when exiting the app and when toast is being shown


Below is just a best practice to use toast.

You need to declare a "Toast" var like this at the start of the class. Only declaration and no definition.

Toast toastMessage;

Then in your function, whenever you are using it do it like this:

if (toastMessage!= null) 
    toastMessage.cancel();
toastMessage= Toast.makeText(context, "Your message", Toast.LENGTH_LONG);
toastMessage.show();
Harikrishnan
  • 1,474
  • 2
  • 11
  • 25
  • @pinman: If my reply helps you, please remember to mark my reply as an answer. Thanks... – Harikrishnan Dec 04 '19 at 11:55
  • Hi Harikrishnan, Thanks for the fast reply. I've made the suggested changes and edited my question with those changes but that does not seem to of helped. The toasts are still appearing when in the background. I haven't yet implemented the "boast" wrapper mentioned in your link as i'm hoping to this can be resolved without going that far. Any other suggestions? Thanks. – pinman Dec 04 '19 at 12:44
0

You can first determine whether your app is in the foreground, and then show the prompt according to the situation.

method isApplicationInTheBackground

private bool isApplicationInTheBackground()
    {
        bool isInBackground;

        RunningAppProcessInfo myProcess = new RunningAppProcessInfo();
        ActivityManager.GetMyMemoryState(myProcess);
        isInBackground = myProcess.Importance != Android.App.Importance.Foreground;

        return isInBackground;
    }

and use like this:

if(!isApplicationInTheBackground()){
 // show the toast

}else{//don't show the toast

}

Reference from: https://forums.xamarin.com/discussion/134696/how-to-tell-if-android-app-is-in-the-background-or-foreground

Jessie Zhang -MSFT
  • 9,830
  • 1
  • 7
  • 19