Xamarin close Android application on back button

You can use a DepedencyService for closing an app when your physical back button is pressed:

In your UI (PCL), do the following:

protected override bool OnBackButtonPressed()
{
   if (Device.RuntimePlatform == Device.Android)
       DependencyService.Get<IAndroidMethods>().CloseApp();

   return base.OnBackButtonPressed();
}

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()
       {
            Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
       }
   }
}

If you want to exit from App without killing and back to home screen, so that if you want to resume it back from where it get closed. you can do implementing as follows in your related activity.

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

    }

Hope this helps.


I tried this code, it works from my side. Hope this code helps you.

protected override bool OnBackButtonPressed()
    {
        Device.BeginInvokeOnMainThread(async () =>
        {
            var result = await DisplayAlert("Alert!", "Do you really want to exit the application?", "Yes", "No");
            if (result)
            {
                if (Device.OS == TargetPlatform.Android)
                {
                    Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
                }
            }
        });
        return true;
    }