Reputation: 27
I'm making a Xamarin Forms App, and I want to put the ability to go back to the app screen via a hardware Back Button and exit the app when pressed on the first page.
I tried several codes to pass the Page name to OnBackPressed in MainActivity and to terminate the app when the corresponding parameter has the MainPage name.
When a Back Button Event occurs in the page the user is currently viewing, the name of the page is delivered.
(var Pages = Xamarin.Forms.Page.Page) -> Does not working
Apply Environment.Exit(1) in OnBackPressed() function in Page.xaml.cs -> Does not work
Other than that, I tried many ways, but it didn't work.
Is there a way to kill the app with a hardware Back Button?
Upvotes: 1
Views: 805
Reputation: 14224
I can provide an incomplete solution.
At first, the app can be killed with one line code in the android:
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
So you can try to override the OnBackPressed() method in the MainActivity and do a judgement. Such as:
public override void OnBackPressed()
{
base.OnBackPressed();
If() // if the page is the first page. or if a flag is true
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
}
You can also do this in the forms:
protected override bool OnBackButtonPressed()
{
if()//Judge whether the current page is the first page
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
return base.OnBackButtonPressed();
}
Upvotes: 2