Reputation: 812
I am new to Xamarin, and mobile development, i have experience with winforms and .net, but threading and MVVM is not something i am very familiar with.
My code works if you click back, select ok in the dialogue, and then click back again. But i would like to improve it by either:
The code below overrides the backbutton on android, and if it returns true. The commented out parts are my fumblings from earlier.
/// <summary>
/// Gives the user a warning that they are about to close the main page
/// </summary>
public override bool OnAndroidBackButtonPressed()
{
if (this.CloseAppAttempts == 0)
{
try
{
this.device.BeginInvokeOnMainThread(async () =>
{
bool closeApp = await this.DisplayService.DisplayAlertAsync("Close app", "Click the OK button to close the app / or click the back button again to close the app", "Ok", "Cancel");
if (closeApp)
{
// this.DisplayService.CloseAsync();
// this.DisplayService.ExitAsync();
// this.DisplayService.pageStack.Pop();
// await IDisplayService.navigation.PopAsync();
this.CloseAppAttempts++;
// i would like to either call the backbutton programatically here, or close
}
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("===== Debug Message - Closing the app did not work - [ " + ex.Message + " ]");
}
return true;
}
else
{
return false;
}
}
Upvotes: 1
Views: 2306
Reputation: 416
The following code overrides the back button and warns the user before going back:
public class MainActivity : Activity
{
. . .
bool pressed = false;
public override void OnBackPressed()
{
if (!pressed)
{
Toast.Show("Press again to exit"); //Implement the Toast correctly
pressed = true;
}
else
base.OnBackPressed();
}
}
(Add some logic to rearm this Toast, so if the user press the button after a while, it shows again)
The next snippet shows a message (I don't know how to show a message in Xamarin.Android, but the logic is there)
public class MainActivity : Activity
{
. . .
public override void OnBackPressed()
{
if (Alert("Exit?", "Yes", "No"))
base.OnBackPressed();
}
}
On Xamarin.Forms, you need to know what page is being shown, so you won't show the dialog at every page and subpage.
In this case, I used NavigationPage to control all the pages.
public class MainActivity : global::Xamarin.Forms.P . . .
{
. . .
bool pressed = false;
public override void OnBackPressed()
{
if (Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.Count == 1)
{
if (Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack[0].DisplayAlert(
"Confirm exit",
"Do you really want to exit?",
"Yes", "No"))
base.OnBackPressed();
}
else
base.OnBackPressed();
}
}
Upvotes: 1
Reputation: 5314
You can close the app on android with this command:
public void CloseApplication()
{
var activity = (Activity)Forms.Context;
activity.FinishAffinity();
}
Using Xamarin.Forms you can call it through a dependency service.
Upvotes: 1