Xamarin Android阻止后台应用吐司显示

问题描述 投票:0回答:2

我创建了一个xamarin android应用,其中包含了当用户迷路时显示的吐司弹出窗口,然后在我的应用中重新获得互联网连接。

这些举杯正确显示,但是当我的应用程序在后台运行时,即使我丢失/重新注册了互联网连接,甚至在前台的其他应用程序上,我仍然看到举杯。

我已经尝试使用toast类的全局实例,然后在onstop和onpause事件上调用toast.cancel(),下面的代码。有什么想法吗?

//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();
}
android xamarin notifications toast
2个回答
0
投票
请参阅下面的链接,了解与您一样的确切情况。

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


下面只是使用吐司的最佳实践。
您需要在课程开始时像这样声明一个“ Toast”变量。仅声明,无定义。

Toast toastMessage;

然后在您的函数中,无论何时使用它,都应像这样:

if (toastMessage!= null) 
    toastMessage.cancel();
toastMessage= Toast.makeText(context, "Your message", Toast.LENGTH_LONG);
toastMessage.show();

0
投票
方法isApplicationInTheBackground

private bool isApplicationInTheBackground() { bool isInBackground; RunningAppProcessInfo myProcess = new RunningAppProcessInfo(); ActivityManager.GetMyMemoryState(myProcess); isInBackground = myProcess.Importance != Android.App.Importance.Foreground; return isInBackground; }

并像这样使用:

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

}else{//don't show the toast

}

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

© www.soinside.com 2019 - 2024. All rights reserved.