i am trying to implement a way to detect the user's status if online or offline. so i used the lifecycle events in xamarin.forms. i set online flag to false when the app goes to the background, then send it using a signalr hub method:
async protected override void OnSleep()
{
online = false;
if (!string.IsNullOrEmpty(Preferences.Get("userid", "")) && !string.IsNullOrEmpty(Preferences.Get("permission", "")))
{
if (Preferences.Get("permission", "") == "Student")
{
try
{
await SendMessage(Preferences.Get("userid", ""), false);
}
catch (Exception exp)
{
MessagingCenter.Send(this, App.UpdateStatusErrorMessage, exp.Message);
}
await updateuserstatus(Preferences.Get("userid", ""));
}
}
}
but it is not being triggered unless it is the second time or third time the app goes to the background. i tried adding Task.Delay(500) then calling base.OnSleep() but nothing is working. any suggestions? thanks in advance
Since you want to update your presence when the user navigates away from the page, the Page.OnDisappearing Method may be more suitable.
And if you still want use
OnSleepevent, you can try the code below.