How to terminate a Xamarin application?

Nik picture Nik · Mar 25, 2015 · Viewed 63.6k times · Source

How to terminate a Xamarin application from any of the activities?

I have tried both System.Environment.Exit(0) and System.Environment.Exit(1) as well as Finish() and killing all the activities.

It still opens one blank page with default activity name and a black screen.

Is there any specific solution for this?

Answer

Akash Amin picture Akash Amin · Jul 5, 2016

If you are using Xamarin.Forms create a Dependency Service.

Interface

public interface ICloseApplication
{
    void closeApplication();
}

Android : Using FinishAffinity() won't restart your activity. It will simply close the application.

public class CloseApplication : ICloseApplication
{
    public void closeApplication()
    {
        var activity = (Activity)Forms.Context;
        activity.FinishAffinity();
    }
}

IOS : As already suggested above.

public class CloseApplication : ICloseApplication
{
    public void closeApplication()
    {
        Thread.CurrentThread.Abort();
    }
}

UWP

public class CloseApplication : ICloseApplication
{
    public void closeApplication()
    {
        Application.Current.Exit();
    }
}

Usage in Xamarin Forms

var closer = DependencyService.Get<ICloseApplication>();
    closer?.closeApplication();