Back to Blog Home
← all posts

Creating native Android packages and using them in NativeScript

July 31, 2015 — by Kiril Stanoev

In this post I will walk you through the process of creating a jar library which will then be referenced from within a custom NativeScript plugin. 

Why?

​Couple of days ago was the 1.2 release of NativeScript. With this release the support for NativeScript plugins was enhanced to support native libraries. You can now package native iOS and Android libraries into a single npm package and distribute it as a plugin. In the general case you will be able to find already implemented native package for you app, but if you can't find an existing UI for your app you may want to create a custom native component. Because NativeScript is all about bringing you the native user experience right? In this post we will guide you how to create a simple JAR package and embed it into a NativeScript plugin.

How?

I will use Android Studio to create a project and export it to a jar and version 1.2 of NativeScript. The jar will serve the basic purpose of displaying a toast notification as soon as the main view of the NativeScript application loads. This will be the end result.

screen #0

Creating a jar library with Android Studio

Start by creating a new Android Studio project.
 
screen #1

screen #2

screen #3

When the project has finished loading, switch to Project view and expand the app module.
 
screen #4

screen #5

Add a new Java file within org.nativescript.kstanoev.toaster and add the code for showing a toast notification.

screen #6

screen #7

package org.nativescript.kstanoev.toaster;
 
import android.content.Context;
import android.widget.Toast;
 
public class Toaster {
   public void show(Context context) {
       CharSequence text = "Hello NativeScript!";
       int duration = Toast.LENGTH_SHORT;
 
       Toast toast = Toast.makeText(context, text, duration);
       toast.show();
   }
}

The next step is to export the project as jar. Open build.gradle (the one located in the app module) and apply the changes below.
 
screen #8

1. Change the first line

apply plugin: 'com.android.application'

to 

apply plugin: 'com.android.library'

2. Remove applicationId, versionCode and versionName from defaultConfig.

3. Add the following tasks to the bottom of the document.

// task to delete the old jar
task deleteOldJar(type: Delete) {
   delete 'release/ToastPlugin.jar'
}
 
// task to export contents as jar
task exportJar(type: Copy) {
   from('build/intermediates/bundles/release/')
   into('release')
   include('classes.jar')
   // name the plugin
   rename('classes.jar','ToastPlugin.jar')
}
 
exportJar.dependsOn(deleteOldJar, build)

Note: ToastPlugin.jar is the name of your jar. You can give it any name you want.

apply plugin: 'com.android.library'
 
android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0 rc2"
 
    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 22
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
 
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
}
 
// task to delete the old jar
task deleteOldJar(type: Delete) {
    delete 'release/ToastPlugin.jar'
}
 
// task to export contents as jar
task exportJar(type: Copy) {
    from('build/intermediates/bundles/release/')
    into('release')
    include('classes.jar')
    // name the plugin
    rename('classes.jar','ToastPlugin.jar')
}
 
exportJar.dependsOn(deleteOldJar, build)

When you’re done, just sync with gradle.

screen #9

The final step is to export our Android Studio project to a jar. We'll use gradle for this purpose. On the right side of Android Studio you should have a tab called ‘Gradle’.
 
This tab contains various gradle tasks. The one we’re looking for is called exportJar.

screen #11

Double-clicking on the task will run it. Let it do its job. In the meantime you can relax with a beverage. If exportJar has finished without any issues you should have a ToastPlugin.jar file located in the release folder of your project.

screen #12

Now, we’ll leave the jar alone for a moment and focus on creating the NativeScript plugin.

Creating a NativeScript plugin

According the documentation, this is the structure our NativeScript plugin must follow.
 
screen #12_0

For the sake of simplicity let’s assume that our working folder is C:\Work\

In C:\Work\ create a new folder called toastplugin. In the toastplugin folder create a package.json file with the following content.

{
  "name": "nativescript-toaster",
  "version": "0.0.1",
  "main": "index.js",
  "nativescript": {
    "platforms": {
      "android": "1.​2.0"
    }
  }
}

Save and close the file.

While in the toastplugin folder, create a new folder called platforms. Open the platforms folder and create yet another folder called android. Open the android folder and create an AndroidManifest.xml file with the following content.
 
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

Note that showing toast notifications does not require special permissions. I’ve added the internet permission for showing purposes.

Save and close the AndroidManifest.xml file.

While still being in the android folder create a new folder called libs. Open the libs folder and copy/paste your ToastPlugin.jar.

The folder structure has been set up so go up to the toastplugin folder where the package.json file is located. In the toastplugin folder create a new file called index.js. 

index.js will contain the code that exposes the functionality of ToastPlugin.jar
 
screen #13

Open index.js and paste the following content.
 
var application = require("application");
var context = application.android.context;
 
module.exports = {
    showToast: function() {
        var toaster = new org.nativescript.kstanoev.toaster.Toaster();
        toaster.show(context);
    }
};

We're done with the plugin! 

Installing the plugin

Let’s install the plugin we just created. NativeScript allows you to install plugins from a local folder as well as through npm.
 
screen #14

Using the plugin

Installing the plugin is just the first step towards using the functionality of the jar within your NativeScript application. Now open main-page.js (located in C:\Work\toast-test\app\) and paste the following contents.
 
var toaster = require("nativescript-toaster");
function pageLoaded(args) {
    var page = args.object;
     
    // show the toast as soon as the app loads
    toaster.showToast();
}
exports.pageLoaded = pageLoaded;

Also, remove any unnecessary contents from main-page.xml.
 
<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="pageLoaded">
  <StackLayout>
     
  </StackLayout>
</Page>

We're all done. Now, connect your Android phone with a USB and run the NativeScript app using the command tns run android
 
screen #14_0

screen #15

If you want to learn more about using npm modules and NativeScript plugins take a look at this article by @tjvantoll. The documentation and the NativeScript Google group are a great resource if you run into issue.