How to use Java code with NativeScript
Learn how to use custom Java code with NativeScript and generate TypeScript typings from a library module packaged as an AAR file.
I'd like to show you how to use Java code you may write in Android Studio with NativeScript. This solution resulted from implementing the Room Persistence library for NativeScript.
To use the Java code in NativeScript, you have two options as illustrated in the following image from the NativeScript docs:
.
You either use the individual Java classes or package them into a library and use that library. In both cases, you should add the necessary dependencies to the app.gradle. In the case of the Room library, you need to add the following dependencies:
Even if you decide to use the Java classes directly without the .aar and you're using Typescript, you'll still want to generate the .aar file to generate types for IntelliSense and strong type checking.
You can start by writing and testing the code you need in Android Studio. When you're satisfied:
- Convert the project(app module) to a library module by following steps 1-4 at Convert an app module to a library module.
- Package the library module, containing all the classes, into a
.aarfile. The image below shows the steps to take in order to produce the.aarfile:
You can find the generated file at the location shown below:

- Drag and drop the
app-release.aarontoThe Archiveror a similar tool to get theclasses.jarfile that you use to generate the types for IntelliSense. - To generate the types, run
ns typings android –jar <path to the .jar >file from step 4. - Reference the generated
android.d.ts(you can rename it appropriately) file in thereference.d.ts.

Now when you type the full package name(com.ombuweb.testroomdb) the Java classes get suggested in VS Code:

See this NativeScript app demo using the Java code . You can find the Java code here.
Hopefully you found this post useful.
Environment
- The Android Studio in the images: 4.1.1