Skip to content

Instantly share code, notes, and snippets.

@Maxim-Kolmogorov
Created November 14, 2021 09:00
Show Gist options
  • Save Maxim-Kolmogorov/cceee3740febd5215962b9a9acafc82d to your computer and use it in GitHub Desktop.
Save Maxim-Kolmogorov/cceee3740febd5215962b9a9acafc82d to your computer and use it in GitHub Desktop.
Cordova Kotlin Plugin Tutorial
android {
sourceSets {
main.java {
srcDirs += 'src/main/kotlin'
}
}
}
var exec = require('cordova/exec');
exports.start = function (arg0, success, error) {
exec(success, error, 'KotlinToast', 'start', [arg0]);
};
package kotlintoast
import android.util.Log
import android.widget.Toast
import org.apache.cordova.*
import org.json.JSONArray
import org.json.JSONException
class KotlinToast : CordovaPlugin() {
lateinit var context: CallbackContext
@Throws(JSONException::class)
override fun execute(action: String, data: JSONArray, callbackContext: CallbackContext): Boolean {
context = callbackContext
var result = true
try {
if (action == "start") {
val input = data.getString(0)
val output = "Kotlin says \"$input\""
Toast.makeText(webView.context, output, Toast.LENGTH_LONG).show();
callbackContext.success(output)
} else {
handleError("Invalid action")
result = false
}
} catch (e: Exception) {
handleException(e)
result = false
}
return result
}
/**
* Handles an error while executing a plugin API method.
* Calls the registered Javascript plugin error handler callback.
*
* @param errorMsg Error message to pass to the JS error handler
*/
private fun handleError(errorMsg: String) {
try {
Log.e(TAG, errorMsg)
context.error(errorMsg)
} catch (e: Exception) {
Log.e(TAG, e.toString())
}
}
private fun handleException(exception: Exception) {
handleError(exception.toString())
}
companion object {
protected val TAG = "KotlinToast"
}
}
<?xml version='1.0' encoding='utf-8'?>
<plugin id="vverh-digital-kotlin-toast" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<name>KotlinToast</name>
<js-module name="KotlinToast" src="www/KotlinToast.js">
<clobbers target="kotlin" />
</js-module>
<platform name="android">
<config-file target="config.xml" parent="/*">
<preference name="GradlePluginKotlinEnabled" value="true" />
<preference name="GradlePluginKotlinCodeStyle" value="official" />
<preference name="GradlePluginKotlinVersion" value="1.3.50" />
<feature name="KotlinToast">
<param name="android-package" value="kotlintoast.KotlinToast" />
</feature>
</config-file>
<source-file src="src/android/KotlinToast.kt" target-dir="src/main/kotlin/kotlintoast"/>
<source-file src="src/android/build-extras.gradle" target-dir="."/>
</platform>
</plugin>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment