我创建了一个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 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();
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
}