How to exit the App in Xamarin Forms?

Senthamizh picture Senthamizh · Oct 26, 2016 · Viewed 13.3k times · Source

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.

Answer

zholinho picture zholinho · Oct 26, 2016

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.