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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With