Josh Russo
Josh Russo

Reputation: 3241

The appropriate way to leave an Android app? (Xamarin)

I'm developing an Android using Xamarin. The app has a login modal and I would like the behavior of the back button on the login modal to essentially exit the app, as if you were at the end of the navigation stack.

Is this possible?

Upvotes: 0

Views: 359

Answers (2)

Josh Russo
Josh Russo

Reputation: 3241

As the solution that @wishmaster provided does give the appearance of the behavior I was looking for, I marked his as as acceptable.

For completeness though, I did run across a more appropriate solution. There's a MoveTaskToBack() method on the Activity class. So this is what my solution was:

public void CloseApp()
{
    var mainActivity = Forms.Context as MainActivity;
    if (mainActivity != null)
        mainActivity.MoveTaskToBack(true);
}

To explain the context a little more. I'm developing a Xamarin Forms app and this is a method on an interface that's injected into the login Forms page.

Upvotes: 0

wishmaster
wishmaster

Reputation: 1303

If you are displaying the modal on android via a new Activity, override OnBackPressed in the modal activity like so:

public override void OnBackPressed()
{
            Intent intent = new Intent(Intent.ActionMain);
            intent.AddCategory(Intent.CategoryHome);
            intent.SetFlags(ActivityFlags.NewTask);
            StartActivity(intent);
}

Upvotes: 1

Related Questions