Search code examples
androidjarsdkaarnativescript-angular

Call android method (sdk, aar or jar) from nativescript


I need to develop a nativescript app integrated with a sdk android native.

I created a sample app in android studio and generated a aar file, then I build a nativescript plugin using this file.

Finally I included that plugin in nativescript app.

When I tried to access the method exposed in aar file, I got a message saying that the method is not a function.

The first time I tried to create an aar with the following class

(Java)

package com.example.toasterlibrary;
import android.content.Context;
import android.widget.Toast;

public class ToasterMessage {
    public ToasterMessage() {
    }

    public static void show(Context c,String message){
       Toast.makeText(c,message,Toast.LENGTH_SHORT).show();
    }
}

Then tried changing the "show" function so that it is not static

(Java)

public void show(Context context, String message) {
    CharSequence text = "Hello NativeScript!";
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}

By the other hand I built a plugin to call the sdk and I got an error message in de index.js file included in the nativescript plugin, specifically in the line toaster.show (context, "Hello world");

(Plugin Nativescript)

var application = require("application");
var context = application.android.context;

module.exports = {
    showToast: function() {        
       var toaster = new com.example.toasterlibrary.ToasterMessage();        
        toaster.show(context,"Hello world");
    }
};

Finally, this is the file that the plugin uses, this is working properly but I'm including it to give more context

(App Nativescript)

import { Component, OnInit } from "@angular/core";
import * as ToasterMessage  from 'nativescript-toaster'

@Component({
    selector: "ns-items",
    moduleId: module.id,
    templateUrl: "./items.component.html"
})
export class ItemsComponent implements OnInit {

    constructor() { }

    ngOnInit(): void {
        ToasterMessage.showToast();
    }
}

I expect that launch a toast message, but launch the following error:

ERROR TypeError: toaster.show is not a function

This error is at the nativescript plugin after executing this command tns run android:


Solution

  • Looks like you were missing the clean build.

    Whenever you update the AAR file, you may have to perform a clean build otherwise the plugin / project may be pointing to the older version of your library.