How to terminate a Xamarin application?

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?


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();

A simple way to make it work cross platform is by this command:

System.Diagnostics.Process.GetCurrentProcess().CloseMainWindow();

Got it from this link.

EDIT: After using it for a while, I discovered that .CloseMainWindow() don't kill the application, only Closes it (well, thats obvious). If you want to terminate the app (kill), you shoud use the following:

System.Diagnostics.Process.GetCurrentProcess().Kill();

For Android, you can do

Android.OS.Process.KillProcess(Android.OS.Process.MyPid());

iOS explicitly does not provide any API for existing an App. Only the OS can close an App.


For iOS, you can use this code:

Thread.CurrentThread.Abort();

For Android, as @Jason mentioned here:

Android.OS.Process.KillProcess(Android.OS.Process.MyPid());