Confirmation Dialog on back button press event Xamarin.Forms

22,670

Solution 1

    protected override bool OnBackButtonPressed()
    {
        Device.BeginInvokeOnMainThread(async() => {
            var result = await this.DisplayAlert("Alert!", "Do you really want to exit?", "Yes", "No");
            if (result) await this.Navigation.PopAsync(); // or anything else
        });

        return true;
    }

Solution 2

Here's the code that worked for me

protected override bool OnBackButtonPressed()
    {
        Device.BeginInvokeOnMainThread(async () =>
        {
            var result = await this.DisplayAlert("Alert!", "Do you really want to exit?", "Yes", "No");

            if (result)
            {
                System.Diagnostics.Process.GetCurrentProcess().CloseMainWindow(); // Or anything else
            }
        });
        return true;
    }

Solution 3

Easy way to override hardware back button and show a confirmation dialog box to user

protected override bool OnBackButtonPressed()
{
    Device.BeginInvokeOnMainThread(async () =>
    {
        if (await DisplayAlert("Alert", "Are you sure you want to go back ?", "Yes", "No"))
        {
            base.OnBackButtonPressed();

            await Navigation.PopAsync();
         }
    });

    return true;
}

Solution 4

If you are on Mainpage and want to exit your app then this code will help you.

In your UI (PCL)

  protected override bool OnBackButtonPressed()
            {

                Device.BeginInvokeOnMainThread(new Action(async () => {
                    var result = await this.DisplayAlert("Alert!", "Do you really want to exit?", "Yes", "No");

                    if (result)
                    {
                        if (Device.RuntimePlatform == Device.Android)
                            DependencyService.Get<IAndroidMethods>().CloseApp();
                    }
                }));
                return true;
            }

Also create an Interface (in your UI PCL):

public interface IAndroidMethods
{
    void CloseApp();
}

Now implement the Android-specific logic in your Android project:

[assembly: Xamarin.Forms.Dependency(typeof(AndroidMethods))]
namespace Your.Namespace
{
   public class AndroidMethods : IAndroidMethods
   {
       public void CloseApp()
       {
             var activity = (Activity)Forms.Context;
            activity.FinishAffinity();
       }
   }
}

Solution 5

public override void OnBackPressed()
{
    RunOnUiThread(
        async () =>
        {
            var isCloseApp = await AlertAsync(this, "NameOfApp", "Do you want to close this app?", "Yes", "No");

            if (isCloseApp)
            {
                var activity = (Activity)Forms.Context;
                activity.FinishAffinity();
            }
        });
}

public Task<bool> AlertAsync(Context context, string title, string message, string positiveButton, string negativeButton)
{
    var tcs = new TaskCompletionSource<bool>();

    using (var db = new AlertDialog.Builder(context))
    {
        db.SetTitle(title);
        db.SetMessage(message);
        db.SetPositiveButton(positiveButton, (sender, args) => { tcs.TrySetResult(true); });
        db.SetNegativeButton(negativeButton, (sender, args) => { tcs.TrySetResult(false); });
        db.Show();
    }

    return tcs.Task;
}

Xamarin.Android await AlertDialog.Builder

Share:
22,670
Afzal Ali
Author by

Afzal Ali

Updated on January 27, 2021

Comments

  • Afzal Ali
    Afzal Ali over 3 years

    I am stuck at one point in Xamarin.Forms application

    On Back button press simply I want to ask user to confirm whether he really wants to exit or not, "OnBackButtonPressed" I want to show Alert dialog and proceed as user response.

    But "OnBackButtonPressed" is not Async I cannot write await DisplayAlert... Please direct me how should i implement this feature?

    I am using ContentPage as my root Page of NavigationPage

        public class frmHome : ContentPage
    

    Here is the code :

    protected override bool OnBackButtonPressed()
    {
        var result = await  this.DisplayAlert("Alert!", "Do you really want to exit?", "Yes", "No");
    
        if (result)
            {
                //user wants to exit
                //Terminate application
            }
            else
            {
                //Dont do anything
            }
    }