Integrate NativeScript With Google Firebase Notification (FCM ) In Android

In this article, we will learn how to use NativeScript using Angular 2 and TypeScript to build a native Android mobile app that is integrated with Google's Firebase Cloud Messaging (FCM )

In this article, we will learn how to use NativeScript using Angular2 and TypeScript to build a native Android mobile app that is integrated with Google's notification service Firebase Cloud Messaging (FCM).

  1. Install node.js.
  2. Install NativeScript - Open Command Prompt and type the following command.

    npm install -g nativescript

  3. Install Java 1.8

  4. Install Android SDK (23 or later)
  5. Open system properties, then add ANDROID_HOME environment variable and set its value with Android SDK path c:\\Android\android-sdk

    Then, add SDK tools to the PATH variable - %ANDROID_HOME%/tools

  6. You must have at least one AVD (Android Virtual Device) configured on your development machine.

  7. If you don’t have any AVD,  open CMD Prompt and type  " android"

    Open "Tools" menu at the top, then select manage AVDs.

    Click on "Create" button.

    Set AVD Settings.

Create native script app
  1. Create new native script app using existing template (groceries). For this, open the command prompt, browse root folder for the project, and then type

    tns create Groceries --template nativescript-template-ng-groceries

  2. Browse the created project to install required library, using the below command.

    npm install require

  3. Install all libraries.

    npm install

  4. Change component template in NativeApps\Groceries\app\app.component.ts to be as the below code to create login screen.
    1. import {  
    2.     Component  
    3. } from "@angular/core";  
    4. @Component({  
    5.     selector: "my-app",  
    6.     template: `  
    7. <StackLayout>  
    8. <TextField hint="Email Address" keyboardType="email"  
    9. autocorrect="false" autocapitalizationType="none"></TextField>  
    10. <TextField hint="Password" secure="true"></TextField>  
    11. <Button text="Sign in"></Button>  
    12. <Button text="Sign up for Groceries"></Button>  
    13. </StackLayout>  
    14. `  
    15. })  
    16. export class AppComponent {}  
  5. Run the app on Android

    tns run android

    This command will create an Android platform in C:\NativeApps\Groceries\platforms
Integrate NativeScript with FCM

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. Now, we will integrate our NativeScript app with Firebase.
  1. Install clipboard plugin to copy Firebase registered device key later.

    tns plugin add nativescript-clipboard

  2. Install Firebase plugin.

    tns plugin add nativescript-plugin-firebase

  3. Browse node_modules/nativescript-plugin-firebase to run the setup of Firebase on our app.

    npm run setup

  4. To reset the configuration again, use the below command.

    npm run config

  5. Create googleservices.json file from

    i. Login using your Google account

    ii. Create new project called (for example) NativeApps

    iii. Get app package name from C:\NativeApps\Groceries\package.json
    1. "nativescript": {  
    2.     "id""org.nativescript.Groceries",  
    3.     "tns-android": {  
    4.         "version""2.4.1"  
    5.     }  
    iv. Click on "Add Firebase to your Android app" icon.

    v. Put app package name, then click "ADD APP" button. Click "Continue", then "Finish".

    vi. Then, it will download google-services.json automatically in your download folder.

    vii. Copy google-services.json into C:\NativeApps\Groceries\app\App_Resources\Android

    viii. Update C:\NativeApps\Groceries\app\main.ts to initiate Firebase plugin and handle MessageReceivedCallback to display dialog box as well as put device token in clipboard to use it later for sending the notification for specific device.
    1. import {  
    2.     platformNativeScriptDynamic  
    3. } from "nativescript-angular/platform";  
    4. import {  
    5.     AppModule  
    6. } from "./app.module";  
    7. const dialogs = require("ui/dialogs");  
    8. let deviceToken = "";  
    9. setTimeout(function() {  
    10.     let firebase = require("nativescript-plugin-firebase");  
    11.     let clipboard = require("nativescript-clipboard");  
    12.     firebase.init({  
    13.         onPushTokenReceivedCallback: function(token) {  
    14.             dialogs.alert("--onPushTokenReceivedCallback token :" + token);  
    15.             clipboard.setText(token).then(function() {  
    16.                 console.log("OK, copied to the clipboard");  
    17.             });  
    18.             deviceToken = token;  
    19.             console.log("Firebase push token: " + token);  
    20.         },  
    21.         onMessageReceivedCallback: function(message) {  
    22.             dialogs.alert({  
    23.                 title: "Push message: " + (message.title !== undefined ? message.title : ""),  
    24.                 message: JSON.stringify(message),  
    25.                 okButtonText: "OK"  
    26.             });  
    27.             dialogs.alert("--onMessageReceivedCallback deviceToken :" + deviceToken);  
    28.             clipboard.setText(deviceToken).then(function() {  
    29.                 console.log("OK, copied to the clipboard");  
    30.             });  
    31.             // clipboard.setText(deviceToken).then(function() { console.log("OK, copied to the clipboard"); });  
    32.         },  
    33.         //persist should be set to false as otherwise numbers aren't returned during livesync  
    34.         persist: false,  
    35.         //storageBucket: 'gs://',  
    36.         onAuthStateChanged: (data: any) => {  
    37.             console.log(JSON.stringify(data))  
    38.             if (data.loggedIn) {  
    39.                 //nn// BackendService.token = data.user.uid;  
    40.             } else {  
    41.                 //nn// BackendService.token = "";  
    42.             }  
    43.         }  
    44.     }).then(function(instance) {  
    45.         console.log("firebase.init done");  
    46.     }, function(error) {  
    47.         console.log("firebase.init error: " + error);  
    48.     });  
    49. }, 3000);  
    50. platformNativeScriptDynamic().bootstrapModule(AppModule);  
  6. Now, we have to run the app.

    tns run android

  7. Copy c:\NativeScript\Groceries\platforms\android\build\outputs\apk\Groceries-debug.apk to an Android mobile that has an internet connection.

  8. When the app is running, the FCM token for this device will be stored in clipboard, so we can use it to send the notification for this specific device. Later, we can store it in database.

  9. Finally, send notification from Google to the app or to the specific device.

    i. Click on "Notifications" in left menu.

    ii. Click on "Send your first message" and insert message details such as text, app, sound,…

    iii. When sending the message and the app is running, the following screen will display.