Shiro Shiro - 6 months ago 733
Android Question

Xamarin close Android application on back button

I tried 3 different ways

if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
System.Environment.Exit(0);

public override void OnBackPressed()
{
Finish();
}

public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back)
{
System.Environment.Exit(0);
return true;
}
return base.OnKeyDown(keyCode, e);
}


None of the above seems to be working

Answer

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.OS == TargetPlatform.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 JetAdvice_Free.Droid.Services
{
   public class AndroidMethods : IAndroidMethods
   {
       public void CloseApp()
       {
            Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
       }
   }
}