[Solved] AndroidGameActivity - OnBackPressed not working

Resolution:


Hey all,

I’m trying to implement some back button functionality for my game and I’m encountering some strange behaviour. If I create a new MonoGame project with all default settings and, in Activity1, override OnBackPressed to have the following…

public override void OnBackPressed()
{
    base.OnBackPressed();

    System.Diagnostics.Debug.WriteLine("AndroidGameActivity.OnBackPressed occurred.");
}

… Then run the game and press the back button, I never get the debug statement, nor does a breakpoint in there get it.

I did some googling around and others have logged this issue, as far back as 2015, and I didn’t see any resolutions. This kind of seems like a bug; however, that same googling yielded a workaround.

If I do the following in my Update method…

public void Update(GameTime gameTime)
{
  if (GamePad.GetState(0).IsButtonDown(Buttons.Back))
    System.Diagnostics.Debug.WriteLine("Back button is down.");
}

… I actually do get the debug statement.

So I want to check in and see if this is intended or not. For those of you who have developed on Android, is this just how it works or is there something I’m missing?

Thanks!

Which version of MonoGame is this? On develop, I can’t find an OnBackPressed method that can be overridden here:

https://github.com/MonoGame/MonoGame/blob/develop/MonoGame.Framework/Android/AndroidGameActivity.cs

This is on MonoGame 3.6. I suspect the method comes from Activity, which would imply that the problem is outside MonoGame. I did quickly try creating a Xamarin App though and the back button code hits without any issue. I also noticed that pressing the back button immediately task switches the app back to the home screen.

I’m not sure how helpful that is… :slight_smile:

The Back button is indeed intended to be mapped to the Back button on the gamepad. This allows the same code to be used across different platforms, and is how we expect you to handle the Back button on Android. Calling Exit() in the Game class sends the activity to the background, as is supposed to happen on Android.

1 Like

Ok, that works for me, thank you!

One last follow up… is it a safe assumption that Index 0 (Player 1) will work, or should all players be iterated across?

The mapping of device buttons will always be to gamepad 0.

1 Like

Much appreciated, thank you :slight_smile: