nativescript Accessing native apis Write java code in nativescript and use it directly in javascript


This is the image of project structure in Android studio:

enter image description here

This is the image of project structure of nativescript project:

enter image description here

As you see they are same. so we can write java code in nativescript as we write in android studio.

We want to Add Toast to the default app of nativescript. after creating a new nativescript project create a directory the java/org/example directory like this:

enter image description here

create a new file in example directory;

package org.example;

import android.widget.Toast;
import android.content.Context;

public class MyToast{

    public static void showToast(Context context,String text ,String StrDuration ){
      int duration;
      switch (StrDuration){
          case "short":
              duration = Toast.LENGTH_SHORT;
          case "long":
              duration = Toast.LENGTH_LONG;
        Toast.makeText(context,text, Toast.LENGTH_SHORT).show();

Notes: don't forget the package name;


import {Component} from "@angular/core";
let application = require("application");

declare var org:any;
    selector: "my-app",
    templateUrl: "app.component.html",
export class AppComponent {
    public counter: number = 16;

    public get message(): string {
        if (this.counter > 0) {
            return this.counter + " taps left";
        } else {
            return "Hoorraaay! \nYou are ready to start building!";

    public onTap() {
        org.example.MyToast.showToast(,"You pressed the button","short");

now when you press the button it will show a toast;


  1. showToast function accepts context to pass it to Toast.makeText an we passed a context to it in this way
  2. typescript doesn't know what orgis, so we declared it: declare var org:any;