Xamarin Close Android app on back button
Some time in your application, it is needed to prompt user before exit from application. In this article, we will see how you can prompt user on pressing back button with a dialog, questioning whether or not the user wishes to exit the application. So, in this article we are going to learn how to prevent user to exit from application without giving response.
Getting it
Go to your Droid project and open MainActivity.cs file and add below code to your onBackPressed() method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
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; | |
} | |
... |
AlertDialog described here.
As a result of clicks back button user will be asked for confirmation for exit:
Written on July 21, 2018