79

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?

Snostorp
  • 544
  • 1
  • 8
  • 14
Nik
  • 791
  • 1
  • 5
  • 4
  • 5
    FYI, Apple strongly discourages terminating apps. Source: http://developer.apple.com/library/ios/qa/qa1561/_index.html – angak Mar 26 '15 at 12:54

15 Answers15

68

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();
Georgi Koemdzhiev
  • 11,421
  • 18
  • 62
  • 126
Akash Amin
  • 2,741
  • 19
  • 38
  • Thank you! Reading on other threads they said, "can't do this in iOS". It's good to see there IS a way. – Damian Sep 30 '16 at 22:12
  • @Damian - I guess apple won't allow this as its against the convention and in the appstore based iOS native apps apple monitors that the developers are not using any private api to close the app though and I am not sure have you checked if it generates any crash log just a thought – Durai Amuthan.H Mar 01 '17 at 10:09
  • 12
    This worked for Android for me but I had to add [assembly: Dependency(typeof(CloseApplication))] to the CloseApplication class for it to get the dependency service – Stephen Price May 12 '17 at 03:11
  • 1
    I also had to add the dependency. Here's the syntax for anyone else like me who had to think about it for a bit: [assembly: Dependency(typeof(CloseApplication))] namespace MyNamespace.Droid { class CloseApplication : ICloseApplication { public void closeApplication() { var activity = (Activity)Forms.Context; activity.FinishAffinity(); } } } – Matt Apr 12 '18 at 20:40
  • 4
    Just a thought but as Apple tells you not to do this there is a good chance an app using this technique won't get through the apple app store review. – Andy Stannard May 23 '18 at 08:54
44

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();
vhoyer
  • 764
  • 8
  • 16
31

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.

Jason
  • 86,222
  • 15
  • 131
  • 146
  • I had apply this code but this also returns me the same black page with title of the main activity....Is there any other solution or am i missing anything over there? – Nik Mar 27 '15 at 14:14
  • Use this if you want terminate all the application processes. (Timers, services, etch...) – jase Jun 25 '18 at 07:20
  • @Zam this may not be valid for newer versions of Android, but it has nothing to do with the version of the IDE that you use – Jason Dec 30 '18 at 00:46
  • This works for my app, on Android 11. Have not tested beyond that yet. – ToolmakerSteve Dec 06 '22 at 02:36
14

For iOS, you can use this code:

Thread.CurrentThread.Abort();

For Android, as @Jason mentioned here:

Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
IdoT
  • 2,831
  • 1
  • 24
  • 35
  • I had apply this code but this also returns me the same black page with title of the main activity....Is there any other solution or am i missing anything over there? – Nik Mar 27 '15 at 14:14
  • 3
    Well, it works for my app. Maybe you're not calling it from the main UI thread? try to terminate the app inside this lambda expression: Xamarin.Forms.Device.BeginInvokeOnMainThread( () => {Android.OS.Process.KillProcess(Android.OS.Process.MyPid());}); Let me know if it helps. – IdoT Mar 27 '15 at 14:47
  • Thanks for your response.And yes i want to terminate the app from child thread,not the main UI thread and my project is in Xamarin.Android not in Xamarin.Forms so can you give me the solution for that? Thanks once again – Nik Apr 01 '15 at 07:56
  • 2
    You have to be on the main thread in order to close the app. try this code: Acitivty.RunOnUiThread(() => { Android.OS.Process.KillProcess(Android.OS.Process.MyPid()); }); – IdoT Apr 01 '15 at 08:37
  • Ok..I am able to achieve this using int pid = Android.OS.Process.MyPid();Android.OS.Process.KillProcess(pid); but it still shows run my application in background..is there any specific code for that? – Nik Apr 10 '15 at 10:20
  • Do you want to remove your app from the background running apps? It's not a standard behavior for the user. – IdoT Apr 11 '15 at 16:16
12

System.Environment.Exit(0);

Works for me.

Samir Bhatt
  • 3,041
  • 2
  • 25
  • 39
Dwight
  • 673
  • 7
  • 15
7

In your activity, use this code

this.FinishAffinity();
Lee Yeong Guang
  • 146
  • 1
  • 6
6

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.

Nitika Chopra
  • 1,281
  • 17
  • 22
3

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;
    }
AhHatem
  • 1,415
  • 3
  • 14
  • 23
  • 2
    I don't think this actually closes the app. It makes the window go away, but the app is still running... at least the debugger doesn't exit when run in a simulator. – Karen Cate May 03 '18 at 23:55
  • 1
    All instanced classes also remain in memory... And when you relaunch their instances are already here full of previous data. – Nick Kovalsky Nov 19 '18 at 07:20
3
System.Diagnostics.Process.GetCurrentProcess().CloseMainWindow();
phrogg
  • 888
  • 1
  • 13
  • 28
VadimP
  • 51
  • 2
2
System.Diagnostics.Process.GetCurrentProcess().Kill();
M. Hamza Rajput
  • 7,810
  • 2
  • 41
  • 36
1

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);
}
phrogg
  • 888
  • 1
  • 13
  • 28
1

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.

GaryP
  • 223
  • 2
  • 13
  • Not necessarily. (Or more accurately, it depends on Android API level, and vendor's implemention.) I can prove this on my device by POWERING OFF. When power back on, the list shows all RECENTLY USED apps. Even though NO apps are running. (I have disabled or deleted any apps that use background services.) Proving that, at least on this device, that is NOT a list of "Open Apps" - it is a list of "Recently Used Apps" (minus any that have been manually swiped away). "Close all" does clear that list. Where the list would be, is text saying "No **recently used** apps.". (emphasis added). – ToolmakerSteve Jun 07 '22 at 23:18
0

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.

Daniel Maclean
  • 779
  • 10
  • 21
0

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

walieeldin
  • 38
  • 10
0

Call

public void Quit ();

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

cigien
  • 57,834
  • 11
  • 73
  • 112
Nabil Akhlaque
  • 192
  • 1
  • 8