简体   繁体   中英

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

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

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.

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;
    }

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;
}
public override void OnBackPressed()
{
    Finish();
    Android.OS.Process.KillProcess (Android.OS.Process.MyPid ());
}

Try this in your activity:

this.FinishAffinity();

Good luck!!

Finish(); 

Worked for me. Executed from the main activity.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM