I am currently trying to constantly keep track whether the user is connected to internet or not.
I have the codes to check for connectivity and I want to be able to show a popup whenever the user is not connected to internet while using the app.
However, I can't put DisplayAlert
at App.cs
(Error: DisplayAlert does not exist in context).
May I know why is this so?
App.cs
public App()
{
InitializeComponent();
var seconds = TimeSpan.FromSeconds(1);
Xamarin.Forms.Device.StartTimer(seconds,
() =>
{
CheckConnection();
});
}
private async void CheckConnection()
{
if (!CrossConnectivity.Current.IsConnected)
await DisplayAlert("No Internet Connection", "Please connect to Internet", "OK");
else
return;
}
DisplayAlert is a method of the page class. However your app has a 'MainPage' property. So as long as the main page is set (should always be so after it's set during startup) you can use
Application.Current.MainPage.DisplayAlert
or from within App.cs
MainPage.DisplayAlert
So you can do this, is working for me
Device.BeginInvokeOnMainThread(async () =>
{
await Application.Current.MainPage.DisplayAlert("No Internet Connection", "Please connect to Internet", "OK");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With