Wednesday, April 18, 2018

Android close app when back button is pressed using Xamarin c#

Requirement: Close the app when back button is pressed using C# in Xamarin.

Scenario: We may need to close the app when we press back button from app's home page

Code:
Use the following line of code in OnBackPressed event.

public class MainActivity : Activity
{
....
....
...
...

   public override void OnBackPressed()
   {
                base.OnBackPressed();
                var intent = new Intent(this, typeof(MainActivity)); 
                base.Finish();
                System.Environment.Exit(0);
    }
}