Click here to Skip to main content
15,886,519 members
Articles / Web Development / Node.js
Tip/Trick

Integrate NativeScript with Google Firebase Notification (FCM) Using Angular2 and Typescript For Android Devices

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
18 Feb 2017CPOL3 min read 12.2K   1  
Use native script with Angular2 and typescript to build a native Android mobile app that is integrated with Google firebase notification FCM

Introduction

In this article, we will learn how to use nativescript (cross platform framework) with Angular2 and typescript to build a native Android mobile app that is integrated with Google firebase notification FCM.

Background

Build a native mobile app using nativescript which is a cross platform framework that used to build Android and ios apps instead of using Java in Android Studio and xcode in iOS, then integrate the app with Google firebase notification FCM (Firebase Cloud Messaging).

Prerequisites

  1. Install nodejs
  2. Install nativescript globally

    Open command prompt, then type:

    npm install -g nativescript

    Image 1

  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

    Image 2

    Then add sdk tools to the PATH variable %ANDROID_HOME%/tools.

    Image 3

  6. You must have at least one AVD (Android Virtual Device) configured on your development machine.
  7. If you don’t have one AVD:
    1. Open command prompt, then type:
      android

      Image 4

    2. Open tools menu on the top, then select manage AVDs:

      Image 5

    3. Click on create button:

      Image 6

    4. Set AVD settings:

      Image 7

Create Native Script App

  1. Create new native script app using existing template (groceries) by open the command prompt and browse root folder for the project, then type:
    tns create Groceries --template nativescript-template-ng-groceries

    Image 8

    Image 9

  2. Browse the created project to install require library using the below command:
    npm install require

    Image 10

  3. Install all libraries using:
    npm install
  4. Change component template in NativeApps\Groceries\app\app.component.ts to be as the below code to create login screen:
    JavaScript
    import { Component } from "@angular/core";
    	@Component({
    	  selector: "my-app",
    	  template: `
    	   <StackLayout>
    	      <TextField hint="Email Address" keyboardType="email"
    	        autocorrect="false" autocapitalizationType="none"></TextField>
    	      <TextField hint="Password" secure="true"></TextField>
    	      <Button text="Sign in"></Button>
    	      <Button text="Sign up for Groceries"></Button>
    	    </StackLayout>
    	  `
    	})
    	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 native-script 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 native script app with firebase:

  1. Install clipboard plug in to copy firebase registered device key later:
    tns plug in add nativescript-clipboard

    Image 11

  2. Install firebase plug in:
    tns plug in add plug in

    Image 12

  3. Browse node_modules/plug in to run setup of the firebase on our app by type:
    npm run setup

    Image 13

  4. To reset the configuration again use the below command:
    npm run config
  5. Create googleservices json file from https://firebase.google.com/
    1. Login using your Google account:

      Image 14

    2. Create new project called for example: NativeApps:

      Image 15

    3. Get app package name from C:\NativeApps\Groceries\package.json:
      JavaScript
      "nativescript": {
      		    "id": "org.nativescript.Groceries",
      		    "tns-android": {
      		      "version": "2.4.1"
      		    }
    4. Click on add firebase to your Android app icon:

      Image 16

    5. Put app package name, then click ADD App button, then continue, then finish:

      Image 17

    6. Then, it will download google-services.json automatically in your download folder:
    7. Copy google-services.json into C:\NativeApps\Groceries\app\App_Resources\Android
    8. Update C:\NativeApps\Groceries\app\main.ts to initiate fire base plug in and handle MessageReceivedCallback to display dialog box as well as put device token in clipboard to use it later to send the notification for specific device.
      JavaScript
      import { platformNativeScriptDynamic } 
      		from "nativescript-angular/platform";
      import { AppModule } from "./app.module";
      const dialogs = require("ui/dialogs");
      
      let deviceToken ="";
      
      setTimeout(function() {
       let firebase  = require("plug in");
       
       let clipboard = require("nativescript-clipboard");
       firebase.init({
         onPushTokenReceivedCallback: function(token) {
            dialogs.alert("--onPushTokenReceivedCallback token :" + token);
            clipboard.setText(token).then(function() 
            { console.log("OK, copied to the clipboard"); });
            deviceToken=token;
            console.log("Firebase push token: " + token);
         },
         onMessageReceivedCallback: function(message) {
          dialogs.alert({
             title: "Push message: " + 
             (message.title !== undefined ? message.title : ""),
             message: JSON.stringify(message),
             okButtonText: "OK"
           }); 
            dialogs.alert("--onMessageReceivedCallback deviceToken :" + deviceToken);
            clipboard.setText(deviceToken).then(function() 
            { console.log("OK, copied to the clipboard"); });
           // clipboard.setText(deviceToken).then(function() 
           { console.log("OK, copied to the clipboard"); });      
         },
         //persist should be set to false as otherwise numbers aren't returned during livesync
         persist: false,
         //storageBucket: 'gs://yowwlr.appspot.com',
         onAuthStateChanged: (data: any) => {
           console.log(JSON.stringify(data))
           if (data.loggedIn) {
             //nn// BackendService.token = data.user.uid;
           }
           else {
            //nn// BackendService.token = "";
           }
         }
       }).then(
           function (instance) {
             console.log("firebase.init done");
           },
           function (error) {
             console.log("firebase.init error: " + error);
           }
       );
      }, 3000);
      
      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 could store it in database.
  9. Finally, send notification from Google to the app or to specific device:
    1. Click on notification in left menu:

      Image 18

    2. Click on send your first message and insert message details such as text, app, sound,…

      Image 19

    3. When sending the message and the app is running:

      Image 20

      Image 21

Points of Interest

Create native mobile apps using nativescript with Angular2 and typescript without learning Java for Android or xcode for iOS, then integrate the app with Google firebase cloud message (FCM).

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
Egypt Egypt
I am experienced in web development with Microsoft technologies using ASP.NET Core ,C#, ASP.NET MVC, ASP.NET Web Api, ADO.NET ,LINQ, web services. I have a working experience with Model View Controller (MVC), and have been involved in maintaining versions of source code using TFS (Team Foundation Server) 2010. I have also developed web user controls, master pages, validation controls, CSS files using technologies like AJAX Toolkit, JQuery, JavaScript, Telerik UI controls, XML, HTML ,angular 1.4., angular 2 , typescript, SPA single page application.

Comments and Discussions

 
-- There are no messages in this forum --