android_library.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. .. _doc_android_library:
  2. Godot Android library
  3. =====================
  4. The Godot Engine for Android platforms is designed to be used as an `Android library <https://developer.android.com/studio/projects/android-library>`_.
  5. This architecture enables several key features on Android platforms:
  6. - Ability to integrate the Gradle build system within the Godot Editor, which provides the ability to leverage more components from the Android ecosystem such as libraries and tools
  7. - Ability to make the engine portable and embeddable:
  8. - Key in enabling the port of the Godot Editor to Android and mobile XR devices
  9. - Key in allowing the integration and reuse of Godot's capabilities within existing codebase
  10. Below we describe some of the use-cases and scenarios this architecture enables.
  11. Using the Godot Android library
  12. -------------------------------
  13. The Godot Android library is packaged as an AAR archive file and hosted on `MavenCentral <https://central.sonatype.com/artifact/org.godotengine/godot>`_ along with `its documentation <https://javadoc.io/doc/org.godotengine/godot/latest/index.html>`_.
  14. It provides access to Godot APIs and capabilities on Android platforms for the following non-exhaustive use-cases.
  15. Godot Android plugins
  16. ---------------------
  17. Android plugins are powerful tools to extend the capabilities of the Godot Engine
  18. by tapping into the functionality provided by Android platforms and ecosystem.
  19. An Android plugin is an Android library with a dependency on the Godot Android library
  20. which the plugin uses to integrate into the engine's lifecycle and to access Godot APIs,
  21. granting it powerful capabilities such as GDExtension support which allows to update / mod the engine behavior as needed.
  22. For more information, see :ref:`Godot Android plugins <doc_android_plugin>`.
  23. Embedding Godot in existing Android projects
  24. --------------------------------------------
  25. The Godot Engine can be embedded within existing Android applications or libraries,
  26. allowing developers to leverage mature and battle-tested code and libraries better suited to a specific task.
  27. The hosting component is responsible for driving the engine lifecycle via Godot's Android APIs.
  28. These APIs can also be used to provide bidirectional communication between the host and the embedded
  29. Godot instance allowing for greater control over the desired experience.
  30. We showcase how this is done using a sample Android app that embeds the Godot Engine as an Android view,
  31. and uses it to render 3D glTF models.
  32. The `GLTF Viewer <https://github.com/m4gr3d/Godot-Android-Samples/tree/master/apps/gltf_viewer>`_ sample app uses an `Android RecyclerView component <https://developer.android.com/develop/ui/views/layout/recyclerview>`_ to create
  33. a list of glTF items, populated from `Kenney's Food Kit pack <https://kenney.nl/assets/food-kit>`_.
  34. When an item on the list is selected, the app's logic interacts with the embedded Godot Engine to render the selected glTF item as a 3D model.
  35. .. image:: img/gltf_viewer_sample_app_screenshot.webp
  36. The sample app source code can be found `on GitHub <https://github.com/m4gr3d/Godot-Android-Samples/tree/master/apps/gltf_viewer>`_.
  37. Follow the instructions on `its README <https://github.com/m4gr3d/Godot-Android-Samples/blob/master/apps/gltf_viewer/README.md>`_ to build and install it.
  38. Below we break-down the steps used to create the GLTF Viewer app.
  39. .. warning::
  40. Currently only a single instance of the Godot Engine is supported per process.
  41. You can configure the process the Android Activity runs under using the `android:process attribute <https://developer.android.com/guide/topics/manifest/activity-element#proc>`_.
  42. .. warning::
  43. Automatic resizing / orientation configuration events are not supported and may cause a crash.
  44. You can disable those events:
  45. - By locking to a specific orientation using the `android:screenOrientation attribute <https://developer.android.com/guide/topics/manifest/activity-element#screen>`_.
  46. - By declaring that the Activity will handle these configuration events using the `android:configChanges attribute <https://developer.android.com/guide/topics/manifest/activity-element#config>`_.
  47. 1. Create the Android app
  48. ^^^^^^^^^^^^^^^^^^^^^^^^^
  49. .. note::
  50. The Android sample app was created using `Android Studio <https://developer.android.com/studio>`_
  51. and using `Gradle <https://developer.android.com/build>`_ as the build system.
  52. The Android ecosystem provides multiple tools, IDEs, build systems for creating Android apps
  53. so feel free to use what you're familiar with, and update the steps below accordingly (contributions to this documentation are welcomed as well!).
  54. - Set up an Android application project. It may be a brand new empty project, or an existing project
  55. - Add the `maven dependency for the Godot Android library <https://central.sonatype.com/artifact/org.godotengine/godot>`_
  56. - If using ``gradle``, add the following to the ``dependency`` section of the app's gradle build file. Make sure to update ``<version>`` to the latest version of the Godot Android library:
  57. .. code-block:: kotlin
  58. implementation("org.godotengine:godot:<version>")
  59. - If using ``gradle``, include the following ``aaptOptions`` configuration under the ``android > defaultConfig`` section of the app's gradle build file. Doing so allows ``gradle`` to include Godot's hidden directories when building the app binary.
  60. - If your build system does not support including hidden directories, you can `configure the Godot project to not use hidden directories <https://docs.godotengine.org/en/stable/classes/class_projectsettings.html#class-projectsettings-property-application-config-use-hidden-project-data-directory>`_ by deselecting ``Project Settings... > Application > Config > Use Hidden Project Data Directory``.
  61. .. code-block:: groovy
  62. android {
  63. defaultConfig {
  64. // The default ignore pattern for the 'assets' directory includes hidden files and
  65. // directories which are used by Godot projects, so we override it with the following.
  66. aaptOptions {
  67. ignoreAssetsPattern "!.svn:!.git:!.gitignore:!.ds_store:!*.scc:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"
  68. }
  69. ...
  70. - Create / update the application's Activity that will be hosting the Godot Engine instance. For the sample app, this is `MainActivity <https://github.com/m4gr3d/Godot-Android-Samples/blob/master/apps/gltf_viewer/src/main/java/fhuyakou/godot/app/android/gltfviewer/MainActivity.kt>`_
  71. - The host Activity should implement the `GodotHost interface <https://github.com/godotengine/godot/blob/master/platform/android/java/lib/src/org/godotengine/godot/GodotHost.java>`_
  72. - The sample app uses `Fragments <https://developer.android.com/guide/fragments>`_ to organize its UI, so it uses `GodotFragment <https://github.com/godotengine/godot/blob/master/platform/android/java/lib/src/org/godotengine/godot/GodotFragment.java>`_, a fragment component provided by the Godot Android library to automatically host and manage the Godot Engine instance.
  73. .. code-block:: kotlin
  74. private var godotFragment: GodotFragment? = null
  75. override fun onCreate(savedInstanceState: Bundle?) {
  76. super.onCreate(savedInstanceState)
  77. setContentView(R.layout.activity_main)
  78. val currentGodotFragment = supportFragmentManager.findFragmentById(R.id.godot_fragment_container)
  79. if (currentGodotFragment is GodotFragment) {
  80. godotFragment = currentGodotFragment
  81. } else {
  82. godotFragment = GodotFragment()
  83. supportFragmentManager.beginTransaction()
  84. .replace(R.id.godot_fragment_container, godotFragment!!)
  85. .commitNowAllowingStateLoss()
  86. }
  87. ...
  88. .. note::
  89. The Godot Android library also provide `GodotActivity <https://github.com/godotengine/godot/blob/master/platform/android/java/lib/src/org/godotengine/godot/GodotActivity.kt>`_, an Activity component that can be extended to automatically host and manage the Godot Engine instance.
  90. Alternatively, applications can directly create a `Godot <https://github.com/godotengine/godot/blob/master/platform/android/java/lib/src/org/godotengine/godot/Godot.kt>`_ instance, host and manage it themselves.
  91. - Using `GodotHost#getHostPlugins(...) <https://github.com/m4gr3d/Godot-Android-Samples/blob/0e3440f357f8be5b4c63a4fe75766793199a99d0/apps/gltf_viewer/src/main/java/fhuyakou/godot/app/android/gltfviewer/MainActivity.kt#L55>`_, the sample app creates a `runtime GodotPlugin instance <https://github.com/m4gr3d/Godot-Android-Samples/blob/master/apps/gltf_viewer/src/main/java/fhuyakou/godot/app/android/gltfviewer/AppPlugin.kt>`_ that's used to send :ref:`signals <doc_signals>` to the ``gdscript`` logic
  92. - The runtime ``GodotPlugin`` can also be used by ``gdscript`` logic to access JVM methods. For more information, see :ref:`Godot Android plugins <doc_android_plugin>`.
  93. - Add any additional logic that will be used by your application
  94. - For the sample app, this includes adding the `ItemsSelectionFragment fragment <https://github.com/m4gr3d/Godot-Android-Samples/blob/master/apps/gltf_viewer/src/main/java/fhuyakou/godot/app/android/gltfviewer/ItemsSelectionFragment.kt>`_ (and related classes), a fragment used to build and show the list of glTF items
  95. - Open the ``AndroidManifest.xml`` file, and configure the orientation if needed using the `android:screenOrientation attribute <https://developer.android.com/guide/topics/manifest/activity-element#screen>`_
  96. - If needed, disable automatic resizing / orientation configuration changes using the `android:configChanges attribute <https://developer.android.com/guide/topics/manifest/activity-element#config>`_
  97. .. code-block:: xml
  98. <activity android:name=".MainActivity"
  99. android:screenOrientation="fullUser"
  100. android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout"
  101. android:exported="true">
  102. ...
  103. </activity>
  104. 2. Create the Godot project
  105. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  106. .. note::
  107. On Android, Godot's project files are exported to the ``assets`` directory of the generated ``apk`` binary.
  108. We leverage that architecture to bind our Android app and Godot project together by creating the Godot project in the Android app's ``assets`` directory.
  109. Note that it's also possible to create the Godot project in a separate directory and export it as a `PCK or ZIP file <https://docs.godotengine.org/en/stable/tutorials/export/exporting_projects.html#pck-versus-zip-pack-file-formats>`_
  110. to the Android app's ``assets`` directory.
  111. Using this approach requires passing the ``--main-pack <pck_or_zip_filepath_relative_to_assets_dir>`` argument to the hosted Godot Engine instance using `GodotHost#getCommandLine() <https://github.com/godotengine/godot/blob/6916349697a4339216469e9bf5899b983d78db07/platform/android/java/lib/src/org/godotengine/godot/GodotHost.java#L45>`_.
  112. The instructions below and the sample app follow the first approach of creating the Godot project in the Android app's ``assets`` directory.
  113. - As mentioned in the **note** above, open the Godot Editor and create a Godot project directly (no subfolder) in the ``assets`` directory of the Android application project
  114. - See the sample app's `Godot project <https://github.com/m4gr3d/Godot-Android-Samples/tree/master/apps/gltf_viewer/src/main/assets>`_ for reference
  115. - Configure the Godot project as desired
  116. - Make sure the `orientation <https://docs.godotengine.org/en/stable/classes/class_projectsettings.html#class-projectsettings-property-display-window-handheld-orientation>`_ set for the Godot project matches the one set in the Android app's manifest
  117. - For Android, make sure `textures/vram_compression/import_etc2_astc <https://docs.godotengine.org/en/stable/classes/class_projectsettings.html#class-projectsettings-property-rendering-textures-vram-compression-import-etc2-astc>`_ is set to `true`
  118. - Update the Godot project script logic as needed
  119. - For the sample app, the `script logic <https://github.com/m4gr3d/Godot-Android-Samples/blob/master/apps/gltf_viewer/src/main/assets/main.gd>`_ queries for the runtime ``GodotPlugin`` instance and uses it to register for signals fired by the app logic
  120. - The app logic fires a signal every time an item is selected in the list. The signal contains the filepath of the glTF model, which is used by the ``gdscript`` logic to render the model.
  121. .. code-block:: gdscript
  122. extends Node3D
  123. # Reference to the gltf model that's currently being shown.
  124. var current_gltf_node: Node3D = null
  125. func _ready():
  126. # Default asset to load when the app starts
  127. _load_gltf("res://gltfs/food_kit/turkey.glb")
  128. var appPlugin = Engine.get_singleton("AppPlugin")
  129. if appPlugin:
  130. print("App plugin is available")
  131. # Signal fired from the app logic to update the gltf model being shown
  132. appPlugin.connect("show_gltf", _load_gltf)
  133. else:
  134. print("App plugin is not available")
  135. # Load the gltf model specified by the given path
  136. func _load_gltf(gltf_path: String):
  137. if current_gltf_node != null:
  138. remove_child(current_gltf_node)
  139. current_gltf_node = load(gltf_path).instantiate()
  140. add_child(current_gltf_node)
  141. 3. Build and run the app
  142. ^^^^^^^^^^^^^^^^^^^^^^^^
  143. Once you complete configuration of your Godot project, build and run the Android app.
  144. If set up correctly, the host Activity will initialize the embedded Godot Engine on startup.
  145. The Godot Engine will check the ``assets`` directory for project files to load (unless configured to look for a ``main pack``), and will proceed to run the project.
  146. While the app is running on device, you can check `Android logcat <https://developer.android.com/studio/debug/logcat>`_ to investigate any errors or crashes.
  147. For reference, check the `build and install instructions <https://github.com/m4gr3d/Godot-Android-Samples/blob/master/apps/gltf_viewer/README.md>`_ for the GLTF Viewer sample app.