Want some programming help? [close]

NativeScript Tutorial

Introduction

NativeScript is an amazing framework that lets you create cross-platform mobile applications for Android and iPhone using TypeScript. Not only does it allow you to use TypeScript, but you can also use Vue.js or Angular frameworks!

In this guide, I will focus on installing the necessary tools to build an Android application using the Angular framework in Windows.

Installation in Windows

The official setup guide is always the most definitive and up-to-date source to use as a reference.

As always, refer to the official Windows install guide for the most up-to-date instructions.

If you are using Windows, Chocolatey (choco) is the easiest way to install everything. From an admin command prompt run:

choco install nodejs-lts -y
choco install googlechrome -y
choco install android-sdk -y  # Also installs Java 8

This will install things in the following locations by default:

C:\Program Files\nodejs
C:\Program Files (x86)\Google\Chrome
C:\Android\android-sdk
C:\Program Files\Java\jdk1.8.0_221

Also, make sure the environment variables are set properly. In particular, JAVA_HOME and ANDROID_HOME.

# Check the environment variables:
echo %JAVA_HOME%
echo %ANDROID_HOME%
# If you need to set the values:
setx JAVA_HOME "C:\Program Files\Java\jdk1.8.0_221"
setx ANDROID_HOME "C:\Android\android-sdk"

Next, the appropriate version of the Android SDK and build tools must be installed. You can do that with the following command:

"%ANDROID_HOME%\tools\bin\sdkmanager" "emulator" "platform-tools" "platforms;android-28" "build-tools;28.0.3" "extras;android;m2repository" "extras;google;m2repository"

Finally, you need to install the nativescript module with npm:

npm install -g nativescript

After nativescript is installed, you can verify everything is configured properly with:

nativescript doctor

Note that nativescript is interchangeable with tns.

Use NativeScript Sidekick

To make life easier, you can use the NativeScript sidekick, a desktop application that helps you manage and builds. It will make life easier when working with NativeScript. It is not an IDE, just a tool to help build, run, and manage your projects.

It also comes with templates for creating new apps and new pages within apps

Install the sidekick from https://www.nativescript.org/nativescript-sidekick.

Create a new project

The easiest way to start a new project and choose the template is to use the NativeScript Sidekick. Simply choose Create and select the options desired. If you don't want to use the NativeScript Sidekick application you can do it via the command line.

To create a new project, you can use the interactive prompt:

nativescript create

Or you can provide it the arguments in a single command:

nativescript create MyProject --template ng

Build your project layouts and components

At this point, you have a NativeScript app that is ready-to-go. The Angular application is inside the src/ directory, and is just a regular Angular application. You use the Angular router to change pages and all of the data binding and dependency injection works as expected.

The only real difference is the .html template files don't use regular HTML elements, and instead use the widgets from NativeScript. Check out all of the available User Interface Widget Components.

Also refer to the Layouts containers like the GridLayout for specifics on using each layout. For example, when putting an element inside a <GridLayout> you need to specify a col and row. For example, the following component:

<!-- e.g. `home.component.html`-->
<GridLayout>
  <Button row="0" col="0" text="Tap" (tap)="myCallback()"></Button>
</GridLayout>

Build the debug APK file

To build your application and get the .apk file, use build. This will build the debug version. See the next section for building and releasing

nativescript build android

The built APK file with a sample app in debug mode is about 30MB. See the section further down about building a relase version and releasing an app to the Google Play store.

Install APK on device

To install the application without running it, you can use the deploy command like this:

nativescript deploy android

This will build the APK and install it in one step.

Run the application

To run the application on your device or emulator, use the run command. You can also list the available devices.

nativescript run  # Also turns on LiveSync
# If you need a list of available devices
nativescript device android --available-devices
# Use --device to specify device

Another option is to use preview to share and install the app. It will generate a QR code that you can scan with the NativeScript Playground app available in the Google Play store. Personally I don't use this method, and I run it directly on an emulator or physical device using LiveSync, covered later.

The running debug build of the sample application uses about 150MB of RAM. The running release build of a small app uses about 85MB of RAM.

Build the release APK file

To build the release version of an app, you need to sign the APK. You will need a private key in order to do this. You can generate your own key using Java's keytool.

Check out my Java Keytool Tutorial to learn how to use keytool to generate and manage your keys and certificates.

Once you have your keystore file, you should also have the following information:

  • The path to your keystore file
  • The password for the keystore
  • The alias of the key for your app in the keystore
  • The password for the key
tns build android --release --key-store-path <keystore-path> --key-store-password <key-store-password> --key-store-alias <key-alias-name> --key-store-alias-password <key-alias-password>

For example:

tns build android --release \
  --key-store-path "$HOME/.keystore" \
  --key-store-password "Scr3t!" \
  --key-store-alias MyApp \
  --key-store-alias-password "Secr3t"

This will build a release-ready APK that is signed and suitable for distribution. The built release file is a little smaller than the debug version, and is about 22MB for a sample app.

You can provide the --release flag to the build, deploy, and run commands, but you will also need to include all the keystore options too.

Release app on the Google Play Store

In order to release on the Google Play Store, you will need to build the application in release mode and use a keystore to sign the app.

From the NativeScript Sidekick, you can click the 'Publish' button to submit your app to the store.

For more information on releasing to the Google Play Store, check out the official documentation at https://docs.nativescript.org/tooling/publishing/publishing-android-apps.

See my tutorial about publishing apps to the Google Play Store and about keystore and app signing How to Publish Android Apps to Google Play Store.

LiveSync

You could just run tns run to start LiveSync and watch the app on your device, but you can also use the Sidekick app.

In the NativeScript Sidekick app, choose 'Run on device'. This will begin LiveSync. This means that any time you make a change and save it in your code, the change will immediately be pushed to the running app. This allows you to see changes instantly without having to rebuild or restart the app.

Additionally, if you check 'Start Debugger' you will be able to debug on your host machine using Chrome developer tools.

Visual Studio Code Extension

If you use Visual Studio Code as your editor, there is an extension available that will let you set breakpoints to debug and also turn on LiveSync.

Read more about the NativeScript Visual Studio Code Extension.

Once the extension is installed:

  • Go to the Debug tab of VS Code
  • Click the gear icon, and choose 'NativeScript' as the debug environment
  • From the dropdown, choose 'Launch on Android'. This takes a minute or two to load. It is slower than nativescript run on initial launch.
  • Click the play button to start debugging and run the app on your device.

This will turn on LiveSync so any changes made will immediately be reflected. You can also set breakpoints anywhere in your code.

Change application theme

Use the NativeScript theme builder to create a theme and download it.

After you download the .css file from the NativeScript Theme Builder, you simply need to include it in your application. In the Angular application, the file where the CSS imports are stored is src/app.css. For example, if you store the custom.css file right next to the app.css file in your project, your import statements would look like this inside the app.css file. Note that you must be using the default core light theme, and leave it there, as the custom styles supplement this theme.

/* src/app.css */
@import '~nativescript-theme-core/css/core.light.css'; /* nativescript-provided core theme */
@import 'custom.css'; /* your downloaded theme */

Change app icon and splash screen

The easiest way to change your app icon and splash image is using NativeScript Sidekick. In the Sidekick, go to the Assets tab and you can replace each image individually.

Alternatively, to do it manually, replace the images in App_Resources/Android/src/main/res/drawable*.

Using Plugins

In many applications you will want to use more than just the UI elements and Angular. For example, you will need to access sensors on the phone like the light sensor, the camera, or the GPS module to get location. You can access these things using plugins. Keep in mind that most plugins will require your application to obtain additional permissions.

Read more about plugins at https://docs.nativescript.org/core-concepts/plugins. You can browse available plugins in the NativeScript Marketplace. You can also browse Angular-specific examples at https://market.nativescript.org/?tab=samples&framework=angular&category=all_samples. Additionally, plugins by the official NativeScript Team can be viewed at https://market.nativescript.org/author/tns-bot.

Vibrate plugin example

Let's look at the vibrate plugin as an example. Check out the NativeScript vibrate plugin documentation.

To install the plugin, run:

nativescript plugin add nativescript-vibrate

This will install the dependency as well as update the App_Resources/Android/src/main/AndroidManifest.xml to include the permission line, although it seems to work even without this permission in Android 9.

<uses-permission android:name="android.permission.VIBRATE" />
// At the top of your module component.ts file
import * as app from "tns-core-modules/application";


    // Somewhere inside your component class
    doVibrate() {
        let vibrator = new Vibrate();
        vibrator.vibrate();
    }

And inside your Components *.component.html file, create a button to call the vibrate method:

<Button (tap)="doVibrate()" text="Vibrate"></Button>

Now you should have a button that you can tap to make your Android device vibrate.

Camera plugin example

Let's use the camera plugin as another example.

Install the plugin first:

nativescript plugin add nativescript-camera

Double check that the permissions are accurate in the App_Resources/Android/src/main/AndroidManifest.xml file. Even though they are granted here, the permission will also be needed at runtime with a popup.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Now, when the app loads, it will ask for the permissions needed to use the camera. Alternatively, instead of asking for permission in the code, you can use the NativeScript Sidekick to manage all Android permissions in the manifest file, or modify the manifest manually located in App_Resources/Android/src/main/AndroidManifest.xml.

We can look at the available method from the module documentation. The takePicture() method is the one we want. Try adding the line somewhere in your code, for example in the ngOnInit() method of your primary app.component.ts so it runs as soon as the app starts:

import * as camera from "nativescript-camera"; // Add this at the top of the file

    // Inside your component
    takePicture() {
        camera.requestPermissions().then(
            function success() {
                camera.takePicture();
            }, 
            function failure() {
                alert('Camera permissions not granted.');
            }
        );
    }

And in your HTML file:

    <Button (tap)="takePicture()" text="Take picture"></Button>

The camera.takePicture() method will open the camera intent and let the user point and snap the photo, retry, or accept the photo taken. Refer to the camera plugin documentation for more details on usage.

Accessing native Java and Android classes

You can easily access any native Java or Android object. For example, this is how you'd access the Java time object:

alert(java.time.LocalDate.now());

If you try to use it just like this however, you will get an error saying 'Cannot find java'. To resolve this, you need to let TypeScript know that the variable is going to be defined elsewhere. To do this, you simply need to add this line to your code:

// Place at the top of your file
declare var java: any;

To get Intellisense code completion for native Android API, you can install TypeScript definitions. Add tns-platform-declarations as a development depedency:

npm install tns-platform-declarations --save-dev

You can then create

Create a file named reference.d.ts and put it in the root directory of your project and put the following content in it:

/// <reference path="node_modules/tns-platform-declarations/android.d.ts" />
/// <reference path="node_modules/tns-platform-declarations/ios.d.ts" />

You can change android.d.ts for the specific version like android-28.d.ts if needed.

Read more about native API interaction at https://docs.nativescript.org/core-concepts/accessing-native-apis-with-javascript

Android Wear apps

It is possible to build NativeScript apps for Android Wear.

Check out the official blog post on the topic at https://www.nativescript.org/blog/nativescript-app-sample-running-on-android-wear.

Android TV apps

You can build NativeScript apps for Android TV.

Check out the official blog post on the topic at https://www.nativescript.org/blog/building-an-android-tv-app-with-nativescript.

Conclusion

After reading this guide, you should know how to install NativeScript and the dependencies needed to create Android applications in the Windows operating system.

References

Advertisement