dimitris93
dimitris93

Reputation: 4273

Xamarin close Android application on back button

I tried 3 different ways

if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
    System.Environment.Exit(0);

public override void OnBackPressed()
{
    Finish();
}

public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
    if (keyCode == Keycode.Back)
    {
            System.Environment.Exit(0);
            return true;
    }
    return base.OnKeyDown(keyCode, e);
}

None of the above seems to be working

Upvotes: 9

Views: 43219

Answers (8)

fractal4
fractal4

Reputation: 51

Try this solution:

protected override bool OnBackButtonPressed()
{           
    Device.BeginInvokeOnMainThread(async () => 
    {
        var res = await this.DisplayAlert("Do you really want to exit the application?", "","Yes", "No").ConfigureAwait(false);

        if (res) System.Diagnostics.Process.GetCurrentProcess().CloseMainWindow();
    });           
    return true;
}

Upvotes: 1

Demitrian
Demitrian

Reputation: 3230

You can use a DepedencyService for closing an app when your physical back button is pressed:

In your UI (PCL), do the following:

protected override bool OnBackButtonPressed()
{
   if (Device.RuntimePlatform == Device.Android)
       DependencyService.Get<IAndroidMethods>().CloseApp();

   return base.OnBackButtonPressed();
}

Also create an Interface (in your UI PCL):

public interface IAndroidMethods
{
    void CloseApp();
}

Now implement the Android-specific logic in your Android project:

[assembly: Xamarin.Forms.Dependency(typeof(AndroidMethods))]
namespace Your.Namespace
{
   public class AndroidMethods : IAndroidMethods
   {
       public void CloseApp()
       {
            Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
       }
   }
}

Upvotes: 27

Nitika Chopra
Nitika Chopra

Reputation: 1405

I tried this code, it works from my side. Hope this code helps you.

protected override bool OnBackButtonPressed()
    {
        Device.BeginInvokeOnMainThread(async () =>
        {
            var result = await DisplayAlert("Alert!", "Do you really want to exit the application?", "Yes", "No");
            if (result)
            {
                if (Device.OS == TargetPlatform.Android)
                {
                    Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
                }
            }
        });
        return true;
    }

Upvotes: 2

Anastasia
Anastasia

Reputation: 462

You also can ask the user to confirm exit App:

public override void OnBackPressed()
{
    RunOnUiThread(
        async () =>
        {
            var isCloseApp = await AlertAsync(this, "NameOfApp", "Do you want to close this app?", "Yes", "No");

            if (isCloseApp)
            {
                var activity = (Activity)Forms.Context;
                activity.FinishAffinity();
            }
        });
}

public Task<bool> AlertAsync(Context context, string title, string message, string positiveButton, string negativeButton)
{
    var tcs = new TaskCompletionSource<bool>();

    using (var db = new AlertDialog.Builder(context))
    {
        db.SetTitle(title);
        db.SetMessage(message);
        db.SetPositiveButton(positiveButton, (sender, args) => { tcs.TrySetResult(true); });
        db.SetNegativeButton(negativeButton, (sender, args) => { tcs.TrySetResult(false); });
        db.Show();
    }

    return tcs.Task;
}

Xamarin.Android await AlertDialog.Builder

Upvotes: 0

Ravi Anand
Ravi Anand

Reputation: 5524

If you want to exit from App without killing and back to home screen, so that if you want to resume it back from where it get closed. you can do implementing as follows in your related activity.

  public override void OnBackPressed()
    {
        Intent startMain = new Intent(Intent.ActionMain);
        startMain.AddCategory(Intent.CategoryHome);
        startMain.SetFlags(ActivityFlags.NewTask);
        StartActivity(startMain);

    }

Hope this helps.

Upvotes: 5

user489998
user489998

Reputation: 4521

Finish(); 

Worked for me. Executed from the main activity.

Upvotes: 0

raBinn
raBinn

Reputation: 182

Try this in your activity:

this.FinishAffinity();

Good luck!!

Upvotes: 1

jojobarcream
jojobarcream

Reputation: 589

public override void OnBackPressed()
{
    Finish();
    Android.OS.Process.KillProcess (Android.OS.Process.MyPid ());
}

Upvotes: 0

Related Questions