Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 971
dimitris93 Avatar asked May 16 '15 09:05

dimitris93


2 Answers

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());
       }
   }
}
like image 185
Demitrian Avatar answered Sep 19 '22 19:09

Demitrian


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.

like image 44
Ravi Anand Avatar answered Sep 21 '22 19:09

Ravi Anand