Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit the App in Xamarin Forms?

My project is built with master-detail navigation. There are totally three pages in the list named as Resources, Contacts, and Login. Everything works fine in iOS, but when the user presses the Droid/WinPhone devices hardware back button, the app should exit. Is there any app-exit mechanism for Xamarin Forms which will work on all the devices.? (I mean native code not platform dependent) Thanks in advance.

like image 914
Senthamizh Avatar asked Dec 30 '25 21:12

Senthamizh


1 Answers

I did that on this way

In xamarin forms I added interface

public interface INativeHelper
{
    void CloseApp();
}

In android project I made implementation of INativeHelper

public class NativeHelper : INativeHelper
{
    public void CloseApp()
    {
        Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
    }                
}

Implementation of INativeHelper in IOS

public class NativeHelper : INativeHelper
{
    public void CloseApp()
    {
        Process.GetCurrentProcess().CloseMainWindow();
        Process.GetCurrentProcess().Close();
    }       
}

And then just override method OnBackButtonPressed in page in Xamarin.Forms project

protected override bool OnBackButtonPressed()
    {
        INativeHelper nativeHelper = null;
        nativeHelper = DependencyService.Get<INativeHelper>();
        if (nativeHelper != null)
        {
            nativeHelper.CloseApp();
        }  

        return base.OnBackButtonPressed();
    }

I didn't made implementation for WinPhone, but it should be similar.

like image 109
zholinho Avatar answered Jan 06 '26 23:01

zholinho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!