简体   繁体   中英

Xamarin Android prevent background app toast display

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();
}

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM