creator-Android interaction and construction


title: creator-Android interaction and construction
categories: Cocos2dx
tags: [creator, Android, native]
date: 2023-04-04 16:20:39
comments: false
mathjax: true
toc: true

creator-Android interaction and construction


Prequel

  • Publish games across platforms - https://docs.cocos.com/creator/2.2/manual/zh/publish/

Related configuration used

  • creator version 3.7.2
  • sdk api 31
  • ndk version: android-ndk-r25c-windows.zip, https://github.com/android/ndk/wiki

configure sdk, ndk

  • File -> Preferences -> Program Manager

    image-20230404162420360


build structure

  • The first build will generate native templates in the project, which contains different platforms, such as: android

    image-20230404162540950

    • The built as project: build\android-001\proj , open it with as to see the structure
  • structure diagram

    image-20230404163357481

    • So the app directory in the project is the directory we need to configure

js interacts with Android

  • How to use JavaScript on the Android platform to directly call Java methods - https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html

Actual operation process

  1. Add a static method in the entry activity class com.cocos.game.AppActivity

        public static void testApi(final String jsonMsg, final String funcKey) {
          
          
            Log.d(TAG, String.format("--- jsonMsg: %s, funcKey: %s", jsonMsg, funcKey));
    
            CocosHelper.runOnGameThread(new Runnable() {
          
          
                @Override
                public void run() {
          
          
                    CocosJavascriptJavaBridge.evalString("console.log(\"--- call from js\")");
    
                    String msgTxt = "{aaa: \"wolegequ\"}";
                    String keyTxt = "world 222";
                    String callStr = String.format("window['gOnAndroidCall']('%s', '%s')", msgTxt, keyTxt); // gOnAndroidCall 是 js 中注册的全局方法
                    CocosJavascriptJavaBridge.evalString(callStr);
                }
            });
        }
    
  2. Remove this method in the js entry

    @ccclass()
    export class GameMgr extends Component {
          
          
        start() {
          
          
            console.log('--- GameMgr start')
    
            // 注册一个全局方法, 接收 jave 调用
            window["gOnAndroidCall"] = this.onNativeCall.bind(this)
    
            if (sys.platform === sys.Platform.ANDROID) {
          
          
                console.log('--- call ANDROID')
                native.reflection.callStaticMethod("com/cocos/game/AppActivity", "testApi", "(Ljava/lang/String;Ljava/lang/String;)V", "Tom 001", "Betty 002");
            }
        }
    
        onNativeCall(jsonMsg: string, funcKey: string) {
          
          
            console.log(`--- gOnAndroidCall, jsonMsg: ${
            
            jsonMsg}, funcKey: ${
            
            funcKey}, node: ${
            
            this.node.name}`)
        }
    }
    
  3. Build (you need to build if you modify js) -> Generate (you need to generate if you modify java)

  4. installation test

    image-20230404174606949


native development process

I prefer to concentrate all native APIs into a library module, and then export this library as a jar and integrate it into the main project

Same as the native process of unity, refer to: unity-Android library development workflow.md

  1. Development Engineering Structure

    image-20230405215722665

    • app: It is the function library module of native API used in all cocos engines
    • testapp: It is the application module to test the native library module, that is, the module that can package the simplest native apk
    • libservice: It is the API related to cocos used in the app library module
    • libservice: It is the API related to cocos used in the app library module

    After the app library module is developed, pass the testapp main module test, and if there is no problem, export the app library module as a jar, such as: classes.jar

  2. Package project structure

    image-20230405220249975

    • In the as project generated by cocos, import the classes.jar exported above into the main module, and then you can use the APIs in all library modules

Step on the pit

ndk reports an error when generating

  • report error

    Execution failed for task ':TestAtlas:generateJsonModelRelease'.
    > E:\workspace\cocos\TestAtlas\native\engine\android\CMakeLists.txt : C/C++ release|armeabi-v7a : CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
      Please set them or make sure they are set and tested correctly in the CMake files:
      LIB_EGL
          linked by target "cocos_engine" in directory E:/workspace/cocos/TestAtlas/native/engine/android
    
  • The reason is that the ndk version is wrong, try changing to the latest version


The gradle task reports an error when generating

  • report error

    Execution failed for task ':TestAtlas:checkReleaseAarMetadata'.
    > Multiple task action failures occurred:
       > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
          > The minCompileSdk (33) specified in a
            dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
            is greater than this module's compileSdkVersion (android-31).
            Dependency: androidx.appcompat:appcompat-resources:1.6.1.
    
  • The reason is that this library is introduced in a module that the applicationimplementation 'androidx.appcompat:appcompat:1.6.1' module of the project depends on. The specified minimum compiled sdk of this library is 33, while the specified compiled sdk of the project is 31

  • There are two solutions

    1. Method 1: (recommended) Set the compile sdk of the application module of the project to 33

      android {
              
              
          compileSdkVersion 33
          defaultConfig {
              
              
              targetSdkVersion 33
          }
      }
      
    2. implementation 'androidx.appcompat:appcompat:1.6.1'Method 2: If you don't need it, remove the import in the dependent module


The native method of java could not be found

  • An error cannot be found for the native method

  • The reason may be that the configuration is confused, and the defined native method (because it is not referenced) is killed. The verification method is very simple. Open the apk with the tool jadx to see if the native method is gone.

  • The solution is to ignore the native method in the confusing configuration file proguard-rules.pro

    ####################### 自定义混淆规则
    -keep class com.yang.androidaar.MainActivity{
          
          
      public static <methods>; #保持该类下所有静态方法不被混淆, 这些是 cocos 的 native 方法
    }
    
    
    
    

Guess you like

Origin blog.csdn.net/yangxuan0261/article/details/129978401