| title | Adding Java/Kotlin Code to an application | ||||
|---|---|---|---|---|---|
| contributors |
|
There are different ways to add native code to an Android application. You can add .jar and .aar files, or Java/Kotlin source files in App_Resources/Android/libs and App_Resources/Android/src respectively.
App_Resources/
ββ Android/
β ββ app.gradle
β ββ libs/
β β ββ HelloAndroidLib.aar # Android Archive
β β ββ HelloJavaLib.jar # Java Archive
β ββ src/
β ββ main/
β ββ java/
β β ββ com/example/HelloKotlin.kt # Kotlin source code
β β ββ com/example/HelloJava.java # Java source code
β ββ res/
ββ ... moreDefine the java file in App_Resources/Android/src/main/java.
// HelloJava.java
package com.example;
public class HelloJava {
public String getString() {
return "Hello from Java!";
}
}Given the example above, your JavaScript or TypeScript code can reference the Java code by using the full class name:
const helloJava = new com.example.HelloJava()
console.log('Java says: ' + helloJava.getString())
// prints: Java says: Hello from Java!:::tip Note
When using TypeScript, you may need to generate typings, or alternatively declare the top level package name as any.
declare const com: any:::
When using Kotlin, it must be enabled first.
Set useKotlin=true in App_Resources/Android/gradle.properties (create the file if it doesn't exist).
useKotlin=trueConfigure the version of Kotlin to use in the application in App_Resources/Android/before-plugins.gradle (create the file if it doesn't exist).
project.ext {
kotlinVersion = "1.9.10"
}Define the kotlin file in App_Resources/Android/src/main/java.
// HelloKotlin.kt
package com.example
class HelloKotlin {
val hello = "Hello from Kotlin!"
}Given the example above, your JavaScript or TypeScript code can reference the Kotlin code by using the full class name:
const helloKotlin = new com.example.HelloKotlin()
console.log('Kotlin says: ' + helloKotlin.hello)
// prints: Kotlin says: Hello from Kotlin!:::tip Note
When using TypeScript, you may need to generate typings, or alternatively declare the top level package name as any.
declare const com: any:::