I have had similar issues with back button before.
In my app I have a login page where the user submits their phone number and then they are taken to a page where they enter the verification code that hey have received. If the user pressed the back button on that page, the app gets minimized but when it's opened again the login page is shown instead of the page for submitting the verification code, even though I've specified clearhistory: true.
This is how I navigate:
this.$navigateTo(ConfirmSMS, {
transition: {name: 'slideLeft'},
clearHistory: true
});
You must use clearHistory only if you don't want use to go back to Login back upon pressing back button.
When you press back button and there are no Pages in back stack, application will terminate. It will still appear in recent application but unlike iOS tapping on the recent application will restart it unless it was paused but another activity / home button.
You may override back button to pause application instead of terminating it.
import { isAndroid } from "#nativescript/core/platform";
import * as application from "#nativescript/core/application";
import { Frame } from "#nativescript/core/ui/frame";
if (isAndroid) {
application.android.on(application.AndroidApplication.activityBackPressedEvent, function (args) {
const frame = Frame.topmost();
if (frame && !frame.canGoBack()) {
args.cancel = true;
var startMain = new android.content.Intent(
android.content.Intent.ACTION_MAIN
);
startMain.addCategory(android.content.Intent.CATEGORY_HOME);
startMain.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
application.android.foregroundActivity.startActivity(startMain);
}
});
}
Playground Sample
Related
I am using xamarin forms prism.
Quick info : I have a page that contains information, this page the user can delete along with its information, this page is an instance of a page called saved conversation, think of each instance as a saved email, you may have many of the one type and are made dynamically.
The user deletes one saved conversation and this also removes an instance for that page, after they have deleted it, it will send them back to one of two pages every time. But they are still able to access this deleted saved conversation page using the hardware back button (Android), either by clicking it straight after they were force navigated back or navigating the app a bit and then pressing the back button multiple times. I would use something such as...
protected override bool OnBackButtonPressed()
{
return true;
}
But I want the back button to work for other pages and only not work if the previous page is an instance of the Saved conversation page, regardless if it has been deleted or not (As I think I may be able to figure out if it was deleted or not myself, just need to detect the page the hardware back button is going to send the user to, I think).
This might fall under a user experience decision over a technical workaround; but it sounds to me like this page you have might be a good candidate to be a Modal Page.
Navigating away from the modal page (popping it from the stack) should accomplish the same goal you are aiming for: not being able to navigate "back" to that page.
What I have done was add this code to all the pages in which I did not want the user to be able to go back. But it would only limit them from going back if the previous page is one of the two shown below. If it isn't then the back button works.
What I did note was you have to make sure modalNavigation is set to false when navigating to the pages (in my case conversation and saved conversation) otherwise they won't appear on the navigation stack to check against.
/// <summary>
/// Will override the harware back button.
/// </summary>
/// <returns> True if it can't go back false if it can.</returns>
protected override bool OnBackButtonPressed()
{
int count = this.Navigation.NavigationStack.Count;
bool shouldntGoBack = false;
if (count > 1)
{
string previousPage = this.Navigation.NavigationStack[count - 2].ToString();
if (previousPage == "NGT.Views.ConversationPage" || previousPage == "NGT.Views.SavedConversationPage")
{
shouldntGoBack = true;
}
}
return shouldntGoBack;
}
What I want to achieve is that the app starts with a login page and after login the Main page should be show. From there other pages can be opened and normal navigation is allowed.
However, I do not want the users to navigate back to the login page. After the login the main page must be the root of the navigation.
I found lots of information on google on how to do it, but they all don't seem to work for me. Mainly I've been told to make my main page the root by setting MainPage directly to my PageMain that is also in my code now, but it does not works.
Other method should be to remove the login page from the navigation stack, but I can't get that to work. The samples I find compile but on runtime they crash my application saying either I cannot remove the current page or the page I am removing is not found.
Here is my code:
My app starts with PageLogin, for now it just has a button and when you click on it then it opens my PageMain
private void ButtonLogin_Clicked(object sender, EventArgs e)
{
// almost does what I want
Application.Current.MainPage = new PageMain();
// almost does what I want
// make PageMain the new main page, so you cannot go back to the login screen
//Application.Current.MainPage = new NavigationPage(new PageMain());
// error you cannot remove the page you are on
//var _navigation = Application.Current.MainPage.Navigation;
//var _lastPage = _navigation.NavigationStack.LastOrDefault();
////Remove last page
//_navigation.RemovePage(_lastPage);
////Go back
//_navigation.PopAsync();
// error page does not exists
//Application.Current.MainPage.Navigation.RemovePage(this);
//Navigation.PopAsync(); not supported on android
//Navigation.RemovePage(this); not supported on android
}
The MainPage is set in App.xaml.cs like this
public partial class App : Application
{
public App()
{
InitializeComponent();
//MainPage = new NavigationPage(new Pages.PageLogin());
MainPage = new Pages.PageLogin();
}
The code above opens my page PageMain so far so good.
Now when I click on the back button of the device, my app minimizes (or whatever it does on android to hide itself)
This is good because I don't want the user to go back to the login form
But, when I now click on recent apps button on the device, and click on my app to get it back in foreground, it moves back to the login form.
See this vid
How can I avoid that ?
EDIT
I tried setting IsTabStop to false, but also no result
public PageLogin()
{
InitializeComponent();
this.IsTabStop = false;
ButtonLogin.Clicked += ButtonLogin_Clicked;
}
This is a pure Android behavior and has nothing to do with Xamarin.Forms, when pressing the back button while your navigation stack of the app is empty, depending on which Android version is running, it will behave like follow:
Android 11 and lower: The system finishes the activity.
Android 12 and higher:
The system moves the activity and its task to the background instead of finishing the activity. This behavior matches the default system behavior when navigating out of an app using the Home button or gesture.
In most cases, this behavior means that users can more quickly resume your app from a warm state, instead of having to completely restart the app from a cold state...
Source: Back press behavior for root launcher activities.
In your case when you press the back button on the main screen, Android finishes the activity, if you want to confirm that, set a breakpoint on your AppShell.cs constructor or MainActivity.cs/OnCreate() you will notice that:
Home button pressed on main screen and restore back the app from android apps stack: none of the breakpoints will be hit because the app activity was conserved. In fact Android will call MainActivity.OnResume().
Back button press you will hit the breakpoints, because the activity was terminated and you are starting it over.
Some potential solutions
Save and keep an updated record of the logging state on a local DB (SQLite) or a file, at the app startup read this bool and accordingly show or no the login page (set the mainpage).
If you don't want your app to exit upon clicking back button, override OnBackPressed() in your MainActivity with an empty code:
public override void OnBackPressed()
{
}
Send your app to the back (pause it) rather than terminate it:
public override void OnBackPressed() => MoveTaskToBack(true);
More on OnBackPressed()
Related questions
What happens when back button or home or application removed from recent apps
How can you restrict/control the navigation routes the user can visit based on login status/role?
I worked out a method base on CFun's answer that seems to work fine during my tests.
I will show my implementation of this answer here, so it can be used by other people with the same problem.
And by doing so I also give a change to everybody to comment on this implementation of that answer.
The idea is to keep a reference to the prior page, everytime another page is opened. Then in the MainActivity.cs in the OnBackPressed method I can check if I am on the Root Page (which is my PageMain) or not.
When on the root page I can do MoveTaskToBack and otherwise I can set the current page to priorPage.
Here is the code:
What I did, first in my App.xaml.cs I put this static variable priorPage
public partial class App : Application
{
public static Page priorPage;
public App()
{
InitializeComponent();
MainPage = new Pages.PageLogin();
}
Then when my app starts (first page is the login page) and the user clicks on login, this code will be executed. The variable priorPage will be set to the page that currently is active, before opening a new page
private void ButtonLogin_Clicked(object sender, EventArgs e)
{
App.priorPage = this;
Application.Current.MainPage = new PageMain();
}
The same principle will be used for every page that is opened
private void ButtonSettings_Clicked(object sender, EventArgs e)
{
App.priorPage = this;
Application.Current.MainPage = new PageSettings();
}
And finally, in the MainActivity.cs I can now do this
public override void OnBackPressed()
{
if (App.Current.MainPage is PageMain)
{
MoveTaskToBack(true); // you are on the root, hide the app
}
else if (App.priorPage != null)
{
App.Current.MainPage = App.priorPage; // navigate back to you prior page
}
else
{
base.OnBackPressed();
}
}
I am developing cross platform mobile application using NativeScript + Angular 2.
I want to handle back button click of the current View, i.e. when user clicks on back button in android device, i want to perform an action like killing / removing the current view from the stack.
For ex: In android platform (Native Development) we can use finish() method of the activity for removing it from the stack. We can handle onBackPressed() like -
#Override
public void onBackPressed()
{
finish(); //Removes current Activity from stack
}
So is there any way to handle onBackPressed() and finish() method in NativeScript + angular 2? I googled a lot but didn't find any solution and also tried Frame.goBack() in NativeScript + Angular 2, but didn't worked for me. It works great in NativeScript + JavaScript.
UPDATE
I want to remove view permanently from the stack as it is not needed any more in application. It should display first time when app install.
For ex :
Like Login Screen
1) When app installs then Login screen should display and on next launch of the application, App will automatically skip the Login Screen and move to the Home Screen(This is working fine)
2) But the problem is when i press back button from Home Screen then app navigates to Login screen every time because Login screen still present in STACK. So that's why i want to remove login screen permanently from stack.
What you need to implement going back is to inject Location and use the method back()
import {Location} from '#angular/common';
#Component({ ... })
export class MyComponent {
constructor(private location: Location) { }
public goBack() {
this.location.back();
}
}
At this point when the user goes back, you shouldn't worry about explicitly destroying the view as there is no mobile option for going "forward"
I have built a Meteor app with a mobile app interface (using Ratchet), only designed to be run as an app. On each page, there is a "back" link that takes you back to the parent page. For example, if I go deep inside a hierarchy of page such as this one:
Home > Category > Post
I can use a link in the Post page that will take me back to the Category page. Now, the problem is, if from this Category page I hit the back button, it should have the same behaviour as clicking the back link on the page. (in this case, take me to the Home page) Sadly, this doesn't happen and I get taken back to the Post page.
On iPhone it is not a problem (as far as I know) since there is no actual back button built-in to the device. But on Android it gives me headaches, for example:
Say a user goes to a Post page that he can delete using a button shown on the page. When the post-deletion method finishes, I take the user back to the Category page:
Router.go('categoryPage', {'_id': categoryId});
Problem is: if the user hits the back button after deleting a post, he or she gets taken to a "not found" page, since the previous post has been deleted. Now I can avoid that by adding replaceState: true like this:
Router.go('categoryPage', {'_id': categoryId}, {replaceState: true});
But now when the user hits the back button from the Category page, he or she gets taken to the page that was there before the Post page, which was... the same Category page. So the button just does nothing on the first press.
I also tried to pushState the url of the desired page in each of my template's `rendered̀€ function, to no avail (and what would I put in there for the Home page?):
Template.categoryPage.rendered = function () {
history.pushState(null, null, Router.url('home'));
};
Template.postPage.rendered = function () {
history.pushState(null, null, Router.url('categoryPage', {'_id': this.data.categoryId}));
};
Has anyone tackled this issue and/or would be able to drop some knowledge?
As soon as the back button is pressed, Cordova trigger a "backbutton" event, see there.
By listening to this event you should be able to override the default behavior and do what you want:
document.addEventListener("backbutton", onBackButtonDown, false);
function onBackButtonDown(event) {
event.preventDefault();
event.stopPropagation();
// Do what you want
...
}
I am creating a simple android Login app using PhoneGap and Eclipse and facing problem with android back button.
I want to control the behaviour of back button such as :
If user has been logged in and he/she pressed on back button app should be minimized.
If not logged-in app should get closed after clicking on back button.
I scoured the lots of posts regarding with "Minimizing the app after clicking back button"
but didn't got the solution. Any solution?
You can handel phonegap back button events with the help of
document.addEventListener("backbutton", onBackButtonFire, false);
Handle Application Pause
document.addEventListener("pause", onPause, false);
Handle Application Resume
document.addEventListener("resume", onResume, false);
Define Back Function
function onBackButtonFire()
{
// Check if user is logged in or not.?
if(localStorage.Checklogin=="true")
{
// minimize app here
}
else
{
// Exit the app
navigator.app.exitApp();
}
}
function onPause()
{
//handel pause;
}
function onResume()
{
// handel resume of app
}
store your information about is user logged in in localStorage.Checklogin .
you can find manually pause the application using this link
Manually Make application Pause
The default behaviour of the backbutton is navigate back in the history and to close the app if ther's no more history.
In Cordova/Phonegap, you can build your own event handler for the back button.
See doc here : http://cordova.apache.org/docs/en/3.5.0/cordova_events_events.md.html#backbutton
Then in your event handler, you would use the history api to either navigate back if you're not on the first page or perform your own logic to close/reduce the app depending on user logged or not.
It's easy to close the app : navigator.app.exitApp();
But to reduce it, I don't know if there's an easy thing in phonegap. And I honestly don't think it makes any sence as in android there's the home button which basically reduces the app.
What I do in my app is that if user is logged, I display a dialog to ask the user if he wants to disconnect.