Search code examples
androidxamarin.android

How to make Xamarin.Android app exit when back button clicked twice(confirm message between clicks included)?


In my MainActivity, I overrode the OnBackPressed() method like that

public override void OnBackPressed()
{
    Toast toast = Toast.MakeText(this, "Press again to exit", ToastLength.Short);
    toast.SetMargin(0,0.20f);
    toast.Show();
}

When the user is in MainActivity and clicks the back button once, on-screen appears the message "Press again to exit" this message disappears after few seconds. If the user clicks back button again when this message is on screen I want the application to exit but when the message has disappeared and the user clicks back button I want the message to appear again. I've seen some examples doing that in Java, but I find it hard to adapt these examples to work on Xamarin.Android.


Solution

  • This code works fine.

        long lastPress;
    
        public override void OnBackPressed()
        {
            // source https://stackoverflow.com/a/27124904/3814729
            long currentTime = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
    
            // source https://stackoverflow.com/a/14006485/3814729
            if (currentTime - lastPress > 5000)
            {
                Toast.MakeText(this, "Press back again to exit", ToastLength.Long).Show();
                lastPress = currentTime;
            }
            else
            {
                base.OnBackPressed();
            }
        }
    

    change the time if you want to use short toast length.

    ToastLength.Long = 3500 (ms)

    ToastLength.Short = 2000 (ms)