当前位置:网站首页>Correct posture of cocoscreator's native secondary development

Correct posture of cocoscreator's native secondary development

2022-06-11 02:58:00 Mr feather

development environment

*
  • cocos creator 3.4.2
  • Android Studio Bumblebee | 2021.1.1 Patch 3
  • ndk r21
*

Preface

This article mainly introduces based on Cocos Creator 3.4.2 Of android The original secondary development process and JSB Conduct Android Layer and cocos ts/js The process of layer calling each other . Provide some references for the development partners .

This paper introduces the background and analysis process , If you only need a conclusion, please jump to “ Access to the process ” Title .

Click the card above or scan the QR code at the end of the text to follow the official account , The background to reply ”3.x Android demo“ obtain demo Source code

background

*

Recently, a game under development has entered Android sdk Access related work , This kind of work is relatively simple , According to past experience, it should be free of obstacles ——“ There must be no need to work overtime tonight ! You can date Xiaohua !”

*

But after building the Android project , It is found that the structure is the same as before jsb-link There's a big difference , It is different from the previous project directory structure .

I was in a panic : I won't have to work overtime ?

Some students in the search forum have seriously posted posts, but they still haven't been solved ( The date of the question is 3 month 17 Japan ), The problem is mainly summarized as : I don't know the process of Android secondary development , I don't know which project to open , How to modify a file , The post is as follows : 【 Help post 】 Please ask about the use of Cocos Creator Conduct Android The right posture for native development

The analysis process

Look through the official documents

Build directory document links

Link to secondary development documents

matters needing attention

View local files

/build/android/proj Catalog

  • see /build/android/proj Not found AppActitivy.java Wait for the documents , But exist build.gradle And other Android related documents
  • Use Android Studio Open Directory , You can successfully open and compile

native Catalog

  • see /native/engine/android/app Catalog , There is AndroidMainfest.xml,build.gradle Wait for the documents .

  • see /native/engine/android/app/com/cocos/game, You can see that there is AppActitivy.java It is found that the above is the familiar Android project directory structure ,

  • Use Android Studio Open Directory , Report errors

  1. Follow the document , Use Android Studio open build/android/proj, Found that the above AndroidMainfest.xml,build.gradle, as well as /native/engine/android/app/com/cocos/game/Appactivity, At this time, just switch the display mode to Android that will do

After switching, you can see the relevant native files

adopt android studio Use in windows Explorer opens AppActivty.java You can find AppActivity.java be located native/engine/android/app/src/com/cocos/game Directory

summary : stay build/android/proj Use as Development , The effective documents are located at native/engine/android in , Yes native The directory does version management , At the same time, it is necessary to remove native Under the build Catalog ( The compilation process generates content temporarily ). build/android The directory is creator Configured service Content , Change with the project , No separate version management is required .

Access to the process

Talking Data Complete access example

Next, let's say TalkingData Sdk For example , Introduce the complete secondary development process of Android native project . Download it sdk Open after sdk file : tdsdk Access to the document , Refer to the documentation for access .

1. Build Android natively in the editor , Please refer to the official documentation for options related to construction , This part of the introduction is more detailed

file : Package and publish to the native platform

2. After building , It can be seen in the project directory native、build/android Two directories

3. Use Android Studio open build/android/proj And switch to Android display mode

4. according to sdk Access documents for access

  • 1. Import sdk
*

stay native/engine/android/app/ New under the directory libs Catalog ( Can be found in android studio Pass through show in explore Use windows Explorer opens , Automatically jump to this directory ),

*

stay \native\engine\android\app Create libs Catalog , Copy sdk Medium aar Wait for the file to arrive libs Next , And in app module Of build.gradle Add dependency to

Notice here libs Of the directory aar/jar The file is not talkingdata Access... In the document TalkingdataSDK.jar, It is SaaS_TalkingDataSDK_Android_V5.0.3.jar( download sdk File name provided when ), In connection with other sdk There are often such details in , Care should be taken to avoid being trapped , It leads to overtime and delays the appointment with xiaohua .

2. Configure obfuscation rules

*

open app module Belongs to proguard-rules.pro Add confusion rules

*
  1. In the same way as above, configure permissions according to document requirements

  2. sdk initialization , Interface implementation, etc , The content is similar , I won't go into details . Key code is provided here , For details, please pay attention to the official account at the end of the article , The background to reply “3.x Android demo” obtain demo Source code

TDSDK.java

package com.cocos.sdk;

import android.util.Log;

import com.cocos.game.AppActivity;
import com.cocos.lib.CocosHelper;
import com.cocos.lib.CocosJavascriptJavaBridge;
import com.tendcloud.tenddata.TalkingDataProfile;
import com.tendcloud.tenddata.TalkingDataProfileType;
import com.tendcloud.tenddata.TalkingDataSDK;

public class TDSDK {
    static String AppID = "xxxxxxxxx";
    static String Chanel = "test_channel";

    static  TDSDK s_self = null;

    public static TDSDK getInstance(){
        if (s_self == null){
            s_self  = new TDSDK();
        }
        return  s_self;
    }

    public void init(){
        TalkingDataSDK.init(AppActivity.getContext(),AppID,Chanel, "");
    }

    public static void onResgister(String accountId){
        if (accountId==""){
            accountId = TalkingDataSDK.getDeviceId(AppActivity.getContext());
        }
        TalkingDataProfile profile = TalkingDataProfile.createProfile();
        profile.setName("");
        profile.setType(TalkingDataProfileType.ANONYMOUS);
        TalkingDataSDK.onRegister(accountId, profile,"");
    }

    public static String js2JavaTest(String str1, String str2){
        Log.d("TDSDK", String.format( "js2JavaTest Success param1:%s param2: %s",str1, str2));
        if (s_self!= null) s_self.java2js();
        return "Java Test Success";
    }
    public void java2js(){
        CocosHelper.runOnGameThread (new Runnable() {
            @Override
            public void run() {
                String str1 = "param3";
                String str2 = "param4";

                String funcStr = String.format("window.tdsdk.java2js('%s','%s')",str1,str2);
                Log.d("-----------------------""Start Java2Js");
                CocosJavascriptJavaBridge.evalString(funcStr);
                Log.d("----------------------""End Java2Js");
            }
        });
    }
}

Appactivity.java, It is suggested that you can simply understand android The execution timing and mechanism of each life cycle function .

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // DO OTHER INITIALIZATION BELOW
        SDKWrapper.shared().init(this);
        TDSDK.getInstance().init();
    }
*
  • After the access is completed, you can directly go to
  • as(android studio, Hereinafter unified abbreviation as) Package in , apk Path is generated :android-001\proj\build\sdkDemo\outputs\apk
    android-001 For in creator The architecture task name of the build interface
*
*
  • It can also be in ccc Click generate in the build tool to package . apk Path is generated :\build\android-001\publish android-001 For in creator The architecture task name of the build interface
*
*
  • If it does js Layer code modification , You also need to carry out engineering construction through the editor's construction process , Then generate , Make the code effective .
  • According to the engine design ,native After directory generation , Building again will skip this part of the build , Avoid affecting what has been developed android sdk、native C++ And other native customized content , It is also suggested that take native Directory add git/svn version control .
*
  1. Package test , The successful running , The activation device can be received in the background , Be accomplished !!!

JS/TS And Android Method intermodulation

Android After the layer is connected , You need to achieve java And ts Intermodulation of .

*
  • Official documents : 1. Java Reflection
    Generalization :
  • ts call java:jsb.reflection.callStaticMethod
  • java call ts, Use evalString, Notice the... In the sample code evalString The single and double quotation marks of parameters in the function are used , Avoid error .
*

Example :

  • cocos creator ts Code :
    const classPath = "com/cocos/sdk/TDSDK";
@ccclass('tdsdk')
export class tdsdk {
    private static _instance = null;
    static getInstance(): tdsdk {
        if (tdsdk._instance == null) {
            tdsdk._instance = new tdsdk();
        }
        return tdsdk._instance;
    }
    //js call Java
    js2Java() {
        if (JSB) {
            log("********************start js2Java param1: title param2: content********************");
            let res = jsb.reflection.callStaticMethod(classPath, "js2JavaTest""(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;""title""content");
            log(" Return value ", res);
            log("********************end js2Java param1: title param2: content********************");
        }
    }
    //java call js
    java2js(param1: string, param2: string) {
        if (!JSB) {
        }
        log("java2js success param3: %s param4:%s ", param1, param2);
    }
}

window.tdsdk = tdsdk.getInstance();

Note that the code ends with tdsdk Hang on window On , And in cocos creator Root creation .d.ts File pair tdsdk Make a global statement ( The file name is optional , Don't conflict with what you already have ) It is convenient for code prompt when calling elsewhere ( Elegance never goes out of style global.d.ts:

import { tdsdk } from "./assets/script/tdsdk";
declare global {
    interface Window {
        tdsdk: tdsdk
    }
}
  • Java Code
public static String js2JavaTest(String str1, String str2){
        Log.d("TDSDK", String.format( "js2JavaTest Success param1:%s param2: %s",str1, str2));
        if (s_self!= null) s_self.java2js();
        return "Java Test Success";
    }
    public void java2js(){
        CocosHelper.runOnGameThread (new Runnable() {
            @Override
            public void run() {
                String str1 = "param3";
                String str2 = "param4";

                String funcStr = String.format("window.tdsdk.java2js('%s','%s')",str1,str2);
                Log.d("-----------------------""Start Java2Js");
                CocosJavascriptJavaBridge.evalString(funcStr);
                Log.d("----------------------""End Java2Js");
            }
        });
    }

Pay attention to java call js Code , If you need to operate ui, Please call... In the specified thread (runOnGameThread), Avoid collapse , Here, the specification is established to uniformly call in the specified thread

Running results

*
  • More advanced intermodulation , Please observe Tencent online technology blog of the Ministry of Education Automatic binding scheme article for , It mainly introduces C++ And js Intermodulation :
*

JSB Auto bind

summary

The above introduction completes sdk Access and java、ts Related usage of intermodulation , After mastering it, you should be able to complete most Android sdk The connection of the is working . Feather is going to date Xiaohua .

more

*

. Simple performance optimization ( One ): Starting from knowledge and method

. Declare a custom data array on the editor

. Inclusion optimization guidelines

Irregular 3D Terrain walking

be based on creator3.0 Of 3D change

Fast implementation 3d Parabola drawing

of odd shape - Irregular button implementation

*

Have you lost your skills today ?

More welcome, WeChat official account

原网站

版权声明
本文为[Mr feather]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110231468054.html