How to terminate a Xamarin application?

XamarinTerminate

Xamarin Problem Overview


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?

Xamarin Solutions


Solution 1 - Xamarin

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

Solution 2 - Xamarin

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

Solution 3 - Xamarin

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.

Solution 4 - Xamarin

For iOS, you can use this code:

Thread.CurrentThread.Abort();

For Android, as @Jason mentioned here:

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

Solution 5 - Xamarin

System.Environment.Exit(0);

Works for me.

Solution 6 - Xamarin

In your activity, use this code

this.FinishAffinity();

Solution 7 - Xamarin

I tried this code

protected override bool OnBackButtonPressed()
    {
        Device.BeginInvokeOnMainThread(async () =>
        {
            var result = await DisplayAlert("", "Would you like to exit from application?", "Yes", "No");
            if (result)
            {
                if (Device.OS == TargetPlatform.Android)
                {
                    Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
                }
                else if (Device.OS == TargetPlatform.iOS)
                {
                   Thread.CurrentThread.Abort();
                }
            }
        });
        return true;
    }

In this, iOS and Android application close when a user chooses to terminate the application. Maybe it helps you.

Solution 8 - Xamarin

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

Solution 9 - Xamarin

A simple all-in-one combination of the previous answers, instead of the interface/dependency:

	protected override bool OnBackButtonPressed()
	{
		Device.BeginInvokeOnMainThread(async () =>
		{
			var result = await this.DisplayAlert("Alert!", "want to exit?", "Yes", "No");
            if (result)
            {
#if __ANDROID__
                var activity = (Android.App.Activity)Forms.Context;
                activity.FinishAffinity();
#endif
#if __IOS__
                Thread.CurrentThread.Abort();
#endif
            }
        });
        return true;
	}

Solution 10 - Xamarin

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

Solution 11 - Xamarin

As your original question mentions activities, your question is specifically for Android, you should probably update the question title with that in mind to avoid people looking for a cross-platform solution coming here.

For iOS and Android (say in Xamarin Forms) you can just throw an exception, which while being the "heavy handed" approach, will do the job:

throw new Exception();

As this isn't the best user experience and you may only want to use this for iOS because on Android, you are likely to get a system popup telling you the app crashed. However, unlike other iOS methods like calling exit(0) or calling private iOS methods like "terminateWithSuccess" via a selector, it shouldn't fail app store validation purely based on how you do it. They may still fail you because your app tries to terminate itself.

You may want to implement something different specifically for Android, in which case Jason's answer is sufficient, again if not a little on the nose i.e. using this approach may not allow your app to clean itself up:

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

Either way, you should really question why you need to provide this option. Unlike desktop applications where closing an application is needed because apps reside inside windows which by design allow multi-tasking and are not task orientated, mobile platforms are primarily designed for users to focus on one task at a time. Once the user is finished the task, they should decide to exit this task by clicking the home button, back button or change app (task) button. This really applies to all platforms.

Solution 12 - Xamarin

None of the methods above helped my Xamarin Android app to completely shut down. I tried to close it from Activity B, having Activity A also open under it.

A clever guy left a trick here.

  1. First call FinishAffinity() in Activity B (closes both activities, however, the app is still alive in the background)
  2. Then call JavaSystem.Exit(0) to kill the background app (I think it can be replaced with Android.OS.Process.KillProcess(Android.OS.Process.MyPid()); or System.Diagnostics.Process.GetCurrentProcess().Kill();)

My method to close the app:

private void CloseBtn_Click(object sender, EventArgs e){
    FinishAffinity();
    JavaSystem.Exit(0);
}

Solution 13 - Xamarin

None of these work with Android 8. They all left the app in the background. I can prove this by pressing the close all button and the app is still there.

For my testing I used a brand new simple Android app and tried all of your answers.

Solution 14 - Xamarin

Application.Quit(); I'm assuming you are using C#

Solution 15 - Xamarin

Call

public void Quit ();

This will quit the application the correct way without it "crashing".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNikView Question on Stackoverflow
Solution 1 - XamarinAkash AminView Answer on Stackoverflow
Solution 2 - XamarinvhoyerView Answer on Stackoverflow
Solution 3 - XamarinJasonView Answer on Stackoverflow
Solution 4 - XamarinIdoTView Answer on Stackoverflow
Solution 5 - XamarinDwightView Answer on Stackoverflow
Solution 6 - XamarinLee Yeong GuangView Answer on Stackoverflow
Solution 7 - XamarinNitika ChopraView Answer on Stackoverflow
Solution 8 - XamarinVadimPView Answer on Stackoverflow
Solution 9 - XamarinAhHatemView Answer on Stackoverflow
Solution 10 - XamarinM. Hamza RajputView Answer on Stackoverflow
Solution 11 - XamarinDaniel MacleanView Answer on Stackoverflow
Solution 12 - XamarinNilufar MakhmudovaView Answer on Stackoverflow
Solution 13 - XamarinGaryPView Answer on Stackoverflow
Solution 14 - XamarinwalieeldinView Answer on Stackoverflow
Solution 15 - XamarinNabil AkhlaqueView Answer on Stackoverflow