If you are on the main page and want to exit the application, this code will help you.
In your interface (PCL)
protected override bool OnBackButtonPressed() { Device.BeginInvokeOnMainThread(new Action(async () => { var result = await this.DisplayAlert("Alert!", "Do you really want to exit?", "Yes", "No"); if (result) { if (Device.RuntimePlatform == Device.Android) DependencyService.Get<IAndroidMethods>().CloseApp(); } })); return true; }
Also create an interface (in your PCL interface):
public interface IAndroidMethods { void CloseApp(); }
Now embed Android-specific logic in your Android project:
[assembly: Xamarin.Forms.Dependency(typeof(AndroidMethods))] namespace Your.Namespace { public class AndroidMethods : IAndroidMethods { public void CloseApp() { var activity = (Activity)Forms.Context; activity.FinishAffinity(); } } }
source share