Nativescript android back button

Override The Android Back Button In A NativeScript With Angular Application

Have you ever needed to perform a certain action when the user tries to hit the back button or exit out of your application on Android devices? For example, what if the user was able to back out of your application and you wanted to show a dialog. Or what if you have a video application and you wanted to pause the video when they tap the back button?

Being able to override the functionality of the back button on Android can do great things for your application as long as you don’t abuse it.

We’re going to see how to create a mobile application with NativeScript and Angular that demonstrates overriding the back button on Android, whether that be hardware or software.

Before we see some code, I want to be clear that you should not abuse the ability to override the back button on Android. This also applies to developer mistakes. If the user cannot exit your application, you risk your application being removed from Google Play or receiving a negative review from the user.

Create a New NativeScript with Angular Application

To keep this tutorial easy to understand, we’re going to work with a fresh project. With the NativeScript CLI installed and configured, execute the following command to create a new project:

The above command will create a project titled, android-back-button-project, and it will use Angular rather than NativeScript Core or Vue.js. To be successful with this particular project, we won’t need any external dependencies.

Catching the Back Button Interaction Everywhere

When it comes to overriding the back button, there isn’t a whole lot too it. We can choose to override on a particular page or on all pages. For this example, we’re going to override on all pages.

Take a moment to remember how routing in Angular works. We have an app.component.html file that all routing passes through. For this reason, it makes sense to add our logic to the TypeScript file. Open the project’s app.component.ts file and include the following:

In the above code, notice that we are importing application which contains a bunch of TypeScript type definitions for working with native Android and iOS code.

Once the application has initialized, we can set up a listener for Android:

The above listener will listen for the activityBackPressedEvent event, which is the back button. When the args.cancel value is false the back button will carry on as normal. When the value is true , the back button won’t do the default activity.

A Realistic Use-Case for Overriding the Android Back Button in NativeScript

The above sample code is great, but it doesn’t really get us anywhere in terms of a use-case. Instead, let’s come up with a quick example that might be beneficial for us.

When routing with NativeScript and Angular, there can be some confusion around child routes. For example, if you have three parent routes and three child routes, the back button, by default, will only navigate the parent routes. This means if you are two levels deep in child routes, the back button will navigate too far. We can actually prevent this behavior by overriding how the back button performs.

Читайте также:  Андроид notepad что это

We already have a project created, so we’ll take advantage of it. Go ahead and create the following files and folders:

If you don’t have the mkdir and touch commands in your command line, go ahead and create the directories and files however you see fit. The files are empty as of now, but let’s put down the ground work in our routing and modules files.

Open the project’s app/app.module.ts file and include the following:

Notice that we’ve only imported our soon to be created components and added them to the declarations array of the @NgModule block. Similarly, open the project’s app/app.routing.ts file and include the following:

Again, we’ve imported the components and we’ve designed routes for them. The goal here is to have two parent routes and two child routes so that we can demonstrate navigation in a backwards direction. We’ll start at parent1 , navigate to parent2 which defaults to child1 , navigate to child2 , then completely backwards with the overridden back button.

If you’d like to learn specifically about routing with child components, check out my tutorial titled, Nested Routing in a NativeScript Angular Application for Android and iOS.

We’re going to populate each of the files with code in the order that they are accessed. Starting with the parent1.component.ts file, include the following:

There is nothing particularly interesting with the above TypeScript, so we’re going to look at the HTML found in the project’s parent1.component.html file:

In the HTML we have a single button that will navigate us to the second parent and pass a value. We don’t technically need to pass any values around, but it is a cool extra thing we can learn about.

Now that we’re on the second parent, we can look at the TypeScript found in the parent2.component.ts file:

This file is more or less pretty basic as well with the exception that we’re printing out the passed value from the previous parent page. The second parent in this example is only a passthrough so we have the following single line in our parent2.component.html file:

The first child will look more or less the same as our second parent. Take a look at the child1.component.ts file:

Even though we’re on a child page, we’re choosing to print out the parent ID value. The HTML to pair looks like the following:

In this case, we have a single button. We’ve chosen to hard-code values, but we’re navigating to the second child, from the second parent. We’re using the parent ID and passing a new child ID. Again, ID values really have no relevance in this tutorial, but it is something that might value you in the future.

The final child is a bit different. Take the child2.component.ts file for example:

We’re printing out the parent value that was passed as well as the child value that was passed. This is useful if you have long extravagant routing and components in your application. To wrap things up, let’s look at the child2.component.html file:

It is an empty layout because we don’t really care for this example. Remember, everything I just showed you is more or less setup for the goal that we’re trying to accomplish. We don’t care about ID values, or the components. We just needed some parent routes and some child routes. Remember, the default back button behavior navigates parent routes, not child routes.

Читайте также:  Windows android mtp drivers

Let’s revisit that app.component.ts file from earlier:

When the Android back button is pressed, we check to see if we can navigate backwards. In other words, is the previous screen a component, or is it going to exit the application.

If we can go back, we’ll use the Angular router to do so, not the default device behavior. If we’re at the end of the line, we’ll let the default behavior take over and exit the application.

Conclusion

You just saw more than you asked for when it came to overriding the Android software and hardware back button functionality in a NativeScript with Angular application. Being able to do this with native code and JavaScript is very useful, but can easily be abused, either on purpose or by accident. Be careful how you’re using the Android back button and make sure it doesn’t ruin your user experience.

If you want to learn more about routing and passing data around, check out my tutorial titled, Navigating a NativeScript App with the Angular Router.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Источник

NativeScript handling back button event

I am trying to handle the hardware back button in a NativeScript app. I am using NativeScript version 2.3.0 with Angular.

Here is what I have in main.ts file

I am importing application with

Then in the constrouctor of appComponentModule I am registering the event for activityBackPressed and just doing a console.log.

This does not work.

What am I missing here?

4 Answers 4

I’m using NativeScript with Angular as well and this seems to work quite nicely for me:

Note that hooking into the backPressedEvent is a global thingy so you’ll need to check the page you’re on and act accordingly, per the example above.

Normally you should have an android activity and declare the backpress function on that activity. Using AndroidApplication only is not enough. Try this code:

You can also take a look at this snippet for example

As far as I know, NativeScript has a built-in support for this but it’s not documented at all. Using onBackPressed callback, you can handle back button behaviour for View components (e.g. Frame, Page, BottomNavigation).

What’s tricky here is to find out which view handles back button press in your app. In my case, I used a TabView that contained pages but the TabView itself handled the event instead of current page.

Источник

Detecting the Android Back button in NativeScript

The Android hardware Back button can be a pain to handle. By default it goes back to the previous route, and when route history ends, it exits the app. It’s not necessarily what you’d like. For example when you open a modal dialog, you may want the Back button to close it instead of navigating away from the parent page. You may want to display a confirmation dialog before doing that.

Abducting the Back button event
First of all you’ll need an application-wide event listener. I personally prefer to put it into a service called AppService which handles everything related to the app, the OS and the device itself, but app.component.ts may serve just as fine. The point is to run it once on startup.

Create this method:

Call it from the constructor() or ngOnInit() but don’t forget to check if your app is running on Android:

Читайте также:  Как перезагрузить операционную систему андроид

What have we just achieved? Upon launching our app, when our singleton service initializes, it’ll create an event listener and watch the Back button. If the currently viewed page has its own event listener looking for the BackButton event, it cancels the default action tied to the Back button and notifies the page component that a BackButton event has occurred. The page then does whatever it has to do.

In your page component put this into the ngOnInit() method:

Thus upon pressing the hardware Back button, the doThing() method will be triggered. The second parameter passes the context to the method, in this case this so you can access variables and other methods from inside that method.

Remove the listener in your ngOnDestroy() :

It may not cause a problem if you don’t remove it, as it won’t trigger unless the page is in view anyway. But you absolutely have to disable the listener before opening modal dialogs because pressing the Back button over a modal would trigger the listener in the parent component. In this case disable it before calling ModalDialogService.showModal() and reinitialize it upon in the callback.

At the same time keep in mind that NativeScript handles Angular lifecycle hooks differently from Angular on the web! ngOnDestroy() is not called automatically when navigating away from a page. See my other article on this topic: The curious case of Angular lifecycle hooks in NativeScript.

You may also notice that the Back button sometimes triggers more than once. It’s one of those mysterious bugs which take a lot of your precious time at the worst moments. The bug is actually not in your code but in NativeScript LiveSync. As you change and save your code and LiveSync refreshes the app in the emulator, the listener initiated by the previous build persists. As a result if you refreshed the app nine times, you’ll get nine button presses. Of course why, oh why would this be documented anywhere. So just don’t use LiveSync when tinkering with Android hardware events, and remember those happier times when development tools were straightforward and reliable.

Источник

nativescript | call ngOnInit after android back button Navigation

I have a problem handling the back button , when the user taping the back button the ngOnInit is not triggered and the component is not working as wanted . from what i saw i understand that when taping back its only make the ngOnDestroy fire but not the ngOnInit

this is the lifecycle

open App —> ngOnInit() called

click on some anther component —> ngOnInit() of the new component called

tap back —> ngOnDestroy

Did someone had the same problem and how did you handle it ? thank you

2 Answers 2

After some search i decided to use this solution

in components that i need the ngOnInit to run even if the navigate is from the back button or function i added this

Why do you think ngOnInit should run on back ? it doesn’t

Solution is to use router events :

For example : A Solution to detect back from «/beatles/john/songs/strawberryfields» to «/doors/jim/girlfriend/pam»

Add this method into a shared service :

In the Doors page call it :

Notice that you can use any token from /beatles/john/songs/strawberryfields ( beatles , john , songs , strawberryfields , atles )—-> also in Doors. (substring)

Basically this methods detects where you came from and what is the destination after back .

BTW you might want to say : «well , I don’t know where I am , I only want a situation where a user tapped «back».

Источник

Оцените статью