Godot Android 插件

前言

Android plugins are powerful tools to extend the capabilities of the Godot engine by tapping into the functionality provided by Android platforms and ecosystem.

For example in Godot 4, Android plugins are used to support multiple Android-based XR platforms without encumbering the core codebase with vendor specific code or binaries.

Android 插件

Android 插件系统的第一版(v1)是在 Godot 3 中引入的,与 Godot 4.0 和 4.1 兼容。这个版本能够让开发者使用 Java、Kotlin 和原生功能增强 Godot 引擎。

从 Godot 4.2 开始,废弃了使用 v1 架构构建的 Android 插件。Godot 4.2 为 Android 插件引入了全新的第二版(v2)架构。

v2 架构

备注

Godot Android 插件使用 Gradle 构建系统

与之前的 v1 架构一样,Android 插件仍然是基于 Android 归档库的。

Godot Android 插件 v2 的本质仍然是一个 Android 库,依赖于 Godot Android 库和自定义的 Android 库说明文件。

这个架构能够让 Android 插件通过以下方法扩展功能:

  • Android 平台 API

  • Android 库

  • Kotlin 和 Java 库

  • 原生库(通过 JNI)

  • GDExtension 库

Each plugin has an init class extending from the GodotPlugin class which is provided by the Godot Android library.

The GodotPlugin class provides APIs to access the running Godot instance and hook into its lifecycle. It is loaded at runtime by the Godot engine.

v2 打包格式

v1 Android plugins required a custom gdap configuration file that was used by the Godot Editor to detect and load them. However this approach had several drawbacks, primary ones being that it lacked flexibility and departed from the existing Godot EditorExportPlugin format, delivery and installation flow.

This has been resolved for v2 Android plugins by deprecating the gdap packaging and configuration mechanism in favor of the existing Godot EditorExportPlugin packaging format. The EditorExportPlugin API in turn has been extended to properly support Android plugins.

构建 v2 Android 插件

A github project template is provided at https://github.com/m4gr3d/Godot-Android-Plugin-Template as a quickstart for building Godot Android plugins for Godot 4.2+. You can follow the template README to set up your own Godot Android plugin project.

To provide further understanding, here is a break-down of the steps used to create the project template:

  1. Create an Android library module using these instructions

  2. Add the Godot Android library as a dependency by updating the module’s gradle build file:

    1. dependencies {
    2. implementation("org.godotengine:godot:4.2.0.stable")
    3. }

The Godot Android library is hosted on MavenCentral, and updated for each release.

  1. Create GodotAndroidPlugin, an init class for the plugin extending GodotPlugin.

    • If the plugin exposes Kotlin or Java methods to be called from GDScript, they must be annotated with @UsedByGodot. The name called from GDScript must match the method name exactly. There is no coercing snake_case to camelCase. For example, from GDScript:

      1. if Engine.has_singleton("MyPlugin"):
      2. var singleton = Engine.get_singleton("MyPlugin")
      3. print(singleton.myPluginFunction("World"))
    • If the plugin uses signals, the init class must return the set of signals used by overriding GodotPlugin::getPluginSignals(). To emit signals, the plugin can use the GodotPlugin::emitSignal(…) method.

  2. Update the plugin AndroidManifest.xml file with the following meta-data:

    1. <meta-data
    2. android:name="org.godotengine.plugin.v2.[PluginName]"
    3. android:value="[plugin.init.ClassFullName]" />

Where:

  • PluginName is the name of the plugin

  • plugin.init.ClassFullName is the full component name (package + class name) of the plugin init class (e.g: org.godotengine.plugin.android.template.GodotAndroidPlugin).

  1. Create the EditorExportPlugin configuration to package the plugin. The steps used to create the configuration can be seen in the Packaging a v2 Android plugin section.

构建带 GDExtension 能力的 v2 Android 插件

Similar to GDNative support in v1 Android plugins, v2 Android plugins support the ability to integrate GDExtension capabilities.

A github project template is provided at https://github.com/m4gr3d/GDExtension-Android-Plugin-Template as a quickstart for building GDExtension Android plugins for Godot 4.2+. You can follow the template’s README to set up your own Godot Android plugin project.

Migrating a v1 Android plugin to v2

Use the following steps if you have a v1 Android plugin you want to migrate to v2:

  1. Update the plugin’s manifest file:

    • Change the org.godotengine.plugin.v1 prefix to org.godotengine.plugin.v2
  2. Update the Godot Android library build dependency:

    • You can continue using the godot-lib.<version>.<status>.aar binary from Godot’s download page if that’s your preference. Make sure it’s updated to the latest stable version.

    • Or you can switch to the MavenCentral provided dependency:

      1. dependencies {
      2. implementation("org.godotengine:godot:4.2.0.stable")
      3. }
  3. After updating the Godot Android library dependency, sync or build the plugin and resolve any compile errors:

    • The Godot instance provided by GodotPlugin::getGodot() no longer has access to a android.content.Context reference. Use GodotPlugin::getActivity() instead.
  4. Delete the gdap configuration file(s) and follow the instructions in the Packaging a v2 Android plugin section to set up the plugin configuration.

打包 v2 Android 插件

As mentioned, a v2 Android plugin is now provided to the Godot Editor as an EditorExportPlugin plugin, so it shares a lot of the same packaging steps.

  1. Add the plugin output binaries within the plugin directory (e.g: in addons/<plugin_name>/)

  2. Add the tool script for the export functionality within the plugin directory (e.g: in addons/<plugin_name>/)

    • The created script must be a @tool script, or else it will not work properly

    • The export tool script is used to configure the Android plugin and hook it within the Godot Editor’s export process. It should look something like this:

      ``` @tool extends EditorPlugin

      A class member to hold the editor export plugin during its lifecycle.

      var export_plugin : AndroidExportPlugin

      func _enter_tree():

      1. # Initialization of the plugin goes here.
      2. export_plugin = AndroidExportPlugin.new()
      3. add_export_plugin(export_plugin)
    1. func _exit_tree():
    2. # Clean-up of the plugin goes here.
    3. remove_export_plugin(export_plugin)
    4. export_plugin = null
    5. class AndroidExportPlugin extends EditorExportPlugin:
    6. # Plugin's name.
    7. var _plugin_name = "<plugin_name>"
    8. # Specifies which platform is supported by the plugin.
    9. func _supports_platform(platform):
    10. if platform is EditorExportPlatformAndroid:
    11. return true
    12. return false
    13. # Return the paths of the plugin's AAR binaries relative to the 'addons' directory.
    14. func _get_android_libraries(platform, debug):
    15. if debug:
    16. return PackedStringArray(["<paths_to_debug_android_plugin_aar_binaries>"])
    17. else:
    18. return PackedStringArray(["<paths_to_release_android_plugin_aar_binaries>"])
    19. # Return the plugin's name.
    20. func _get_name():
    21. return _plugin_name
    22. ```
  3. Create a plugin.cfg. This is an INI file with metadata about your plugin:

    1. [plugin]
    2. name="<plugin_name>"
    3. description="<plugin_description>"
    4. author="<plugin_author>"
    5. version="<plugin_version>"
    6. script="<relative_path_to_the_export_tool_script>"

For reference, here is the folder structure for the Godot Android plugin project template. At build time, the contents of the export_scripts_template directory as well as the generated plugin binaries are copied to the addons/<plugin_name> directory:

  1. export_scripts_template/
  2. |
  3. +--export_plugin.gd # export plugin tool script
  4. |
  5. +--plugin.cfg # plugin INI file

Packaging a v2 Android plugin with GDExtension capabilities

For GDExtension, we follow the same steps as for Packaging a v2 Android plugin and add the GDExtension config file in the same location as plugin.cfg.

For reference, here is the folder structure for the GDExtension Android plugin project template. At build time, the contents of the export_scripts_template directory as well as the generated plugin binaries are copied to the addons/<plugin_name> directory:

  1. export_scripts_template/
  2. |
  3. +--export_plugin.gd # export plugin tool script
  4. |
  5. +--plugin.cfg # plugin INI file
  6. |
  7. +--plugin.gdextension # GDExtension config file

Here is what the plugin.gdextension config file should look like:

  1. [configuration]
  2. entry_symbol = "plugin_library_init"
  3. compatibility_minimum = "4.2"
  4. android_aar_plugin = true
  5. [libraries]
  6. android.debug.arm64 = "res://addons/GDExtensionAndroidPluginTemplate/bin/debug/arm64-v8a/libGDExtensionAndroidPluginTemplate.so"
  7. android.release.arm64 = "res://addons/GDExtensionAndroidPluginTemplate/bin/release/arm64-v8a/libGDExtensionAndroidPluginTemplate.so"
  8. ...

Of note is the android_aar_plugin field that specifies this GDExtension module is provided as part of a v2 Android plugin. During the export process, this will indicate to the Godot Editor that the GDExtension native shared libraries are exported by the Android plugin AAR binaries.

For GDExtension Android plugins, the plugin init class must override GodotPlugin::getPluginGDExtensionLibrariesPaths(), and return the paths to the bundled GDExtension libraries config files (*.gdextension).

The paths must be relative to the Android library’s assets directory. At runtime, the plugin will provide these paths to the Godot engine which will use them to load and initialize the bundled GDExtension libraries.

使用 v2 Android 插件

备注

  • 要求 Godot 4.2 或更高版本

  • v2 Android plugin requires the use of the Gradle build process.

  • The provided github project templates include demo Godot projects for quick testing.

  1. Copy the plugin’s output directory (addons/<plugin_name>) to the target Godot project’s directory

  2. Open the project in the Godot Editor; the Editor should detect the plugin

  3. 导航到 项目 -> 项目设置... -> 插件 ,并确保插件已启用

  4. Install the Godot Android build template by clicking on Project -> Install Android Build Template...

  5. Navigate to Project -> Export...

  6. In the Export window, create an Android export preset

  7. In the Android export preset, scroll to Gradle Build and set Use Gradle Build to true

  8. Update the project’s scripts as needed to access the plugin’s functionality. For example:

    1. if Engine.has_singleton("MyPlugin"):
    2. var singleton = Engine.get_singleton("MyPlugin")
    3. print(singleton.myPluginFunction("World"))
  9. Connect an Android device to your machine and run the project on it

Using a v2 Android plugin as an Android library

Since they are also Android libraries, Godot v2 Android plugins can be stripped from their EditorExportPlugin packaging and provided as raw AAR binaries for use as libraries alongside the Godot Android library by Android apps.

If targetting this use-case, make sure to include additional instructions for how the AAR binaries should be included (e.g: custom additions to the Android app’s manifest).

参考实现

技巧与指南

简化对暴露的 Java / Kotlin API 的访问

To make it easier to access the exposed Java / Kotlin APIs in the Godot Editor, it’s recommended to provide one (or multiple) gdscript wrapper class(es) for your plugin users to interface with.

例如:

  1. class_name PluginInterface extends Object
  2. ## Interface used to access the functionality provided by this plugin.
  3. var _plugin_name = "GDExtensionAndroidPluginTemplate"
  4. var _plugin_singleton
  5. func _init():
  6. if Engine.has_singleton(_plugin_name):
  7. _plugin_singleton = Engine.get_singleton(_plugin_name)
  8. else:
  9. printerr("Initialization error: unable to access the java logic")
  10. ## Print a 'Hello World' message to the logcat.
  11. func helloWorld():
  12. if _plugin_singleton:
  13. _plugin_singleton.helloWorld()
  14. else:
  15. printerr("Initialization error")

支持在 Godot 编辑器中使用 GDExtension 的功能

If planning to use the gdextension functionality in the Godot Editor, it is recommended that the gdextension’s native binaries are compiled not just for Android, but also for the OS onto which developers / users intend to run the Godot Editor. Not doing so may prevent developers / users from writing code that accesses the plugin from within the Godot Editor.

This may involve creating dummy plugins for the host OS just so the API is published to the editor. You can use the [godot-cpp-template](https://github.com/godotengine/godot-cpp-template) github template for reference on how to do so.

Godot 在加载时崩溃

检查 adb logcat 是否存在可能的问题,然后:

  • 检查插件暴露的方法是否使用了下列 Java 类型:voidbooleanintfloatjava.lang.Stringorg.godotengine.godot.Dictionaryint[]byte[]float[]java.lang.String[]

  • 暂时不支持更复杂的数据类型.

Previous Next


© 版权所有 2014-present Juan Linietsky, Ariel Manzur and the Godot community (CC BY 3.0). Revision b1c660f7.

Built with Sphinx using a theme provided by Read the Docs.