0
votes

I am stuck at a place for sometime now and cannot find any help on it.

Scenario: I have a Xamarin Forms app. When the app starts, I check if the user is logged in or not. If the user is logged in, I open Main Screen. But if the user is not logged in, I open the login view as Modal page Navigation.PushModalAsync on top of main screen. Once the user is logged in, I remove this page and show my original Main page.

Problem When the user presses Back button on phone, I want the Application to Exit. How can I do that.

Note: I am using Navigation stack to push and pop pages. In this case, I guess, I have to pop all the pages. But I can't figure out how.

2
Do you mean the Hardware Back button? If so, the issue is only for android, right? - Kevin Li

2 Answers

1
votes

Since the back button is only an issue on Android devices, you can override OnBackButtonPressed() to call a dependency service to close the app. In your LoginPage add this:

protected override bool OnBackButtonPressed()
{
    DependencyService.Get<IAndroidMethods>().CloseApp();
    return base.OnBackButtonPressed();
}

I made my dependency service off of my IAndroidMethods interface which I implemented in my MyApp.Droid project:

[assembly: Xamarin.Forms.Dependency(typeof(AndroidMethods))]
namespace MyApp.Droid
{
    public class AndroidMethods : IAndroidMethods
    {
        public void CloseApp()
        {
            //This closes the Android app
            Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
        }
    }
}

Now when the back button is pressed from your login page, the app will close.

0
votes

Inside your MainActivity.cs add this:

public override void OnBackPressed()
{
    if (App.ImInLoginView)
    {
        Finish();
    }
    else
    {
        base.OnBackPressed();
    }
}

Where App.ImInLoginView Is a flag I use as a reference (inside my App.cs):

public static bool ImInLoginView;

Which I turn it on/off in the OnAppearing and OnDisappearing events.

I hope this helps.