Development of HarmonyOS learning path—Java UI framework (use tools to automatically generate JS FA to call PA code)

JS FA (Feature Ability) calling PA (Particle Ability) is a cross-language ability calling mechanism provided by the Ark development framework based on the JS extension-like Web development paradigm, and is used to establish a transfer method between JS capabilities and Java capabilities A channel for calling, processing data returns, and subscribing to event reporting. Developers can use FA to call the PA mechanism for application development, but directly using this mechanism requires developers to manually write a lot of template code, and the template code may be coupled with the business code, making the code poor maintainability and readability.

To improve development efficiency, developers can use the js2java-codegen tool in the DevEco Studio environment to automatically generate JS FA calling PA code (currently only supports the InternalAbility calling method), and quickly complete the development of FA calling PA applications. Developers only need to add simple configurations and annotations to use this tool to complete most of the writing of FA call PA template codes. At the same time, it also effectively separates business codes from template codes, making the codes more maintainable and reliable. readability.

illustrate

For details about JS FA calling PA, please refer to How JS FA Calls PA .

Introduction to js2java-codegen tool

js2java-codegen is an auxiliary development tool provided by the tool chain to automatically generate JS FA calling PA code. It can generate the template code required by the FA to call the PA according to the user's source code, which is separated from the business code written by the user.

The implementation method of FA calling PA supported by the js2java-codegen tool is the InternalAbility type, which currently does not support the Ability type. After the developer completes the settings, he only needs to write the InternalAbility class that contains the actual business logic and the Ability class that needs to be registered, and add corresponding annotations to the InternalAbility class. js2java-codegen can complete the establishment of the FA call PA channel during the compilation process. After that, developers only need to call the JS interface generated by the js2java-codegen tool on the JS side to call the capabilities on the Java side.

The template code generated by the js2java-codegen tool includes Java code and JS code. Among them, the Java code will be directly compiled into a bytecode file, and the registration and de-registration statements will be automatically added to the corresponding Ability class, and the developer does not need to pay attention to it; while the JS code needs to be called manually by the user, so the developer needs to set it before compiling. Good JS code output path.

This feature is supported starting from version 2.2.0.3 of Toolchains in the HarmonyOS SDK.

Annotation Instructions

The js2java-codegen tool obtains information through annotations and generates the code required by the developer. Therefore, if users want to use this tool to assist development, they need to understand the usage of the following three annotations.

  • @InternalAbility annotation

Class annotations for classes that are used as InternalAbility and contain actual business code (InternalAbility class for short). Only public top-level classes in the file are supported, interface classes and annotation classes are not supported.

Contains a parameter: registerTo, whose value is the full name of the Ability class to be registered. For specific use cases, see the Java side code writing section.

The use case is as follows, which means that the Service class is an InternalAbility class, which is registered to the Ability class named Ability located in the com.example package.

@InternalAbility(registerTo = "com.example.Ability")
public class Service{}
  • @ExportIgnore annotation

Method annotations are used for certain methods in the InternalAbility class, indicating that the method is not exposed to the JS side for calling. Valid only for public methods.

The use case is as follows, which means that the service method will not be exposed to the JS side.

@ExportIgnore
public int service(int input) {
    return input;
}
  • @ContextInject annotation

Used for annotations on AbilityContext. This class is provided by the Java API of HarmonyOS, through which developers can obtain the information provided in the API.

The use case is as follows, which means that the developer can use the abilityContext object to obtain the information provided in the API.

@ContextInject
AbilityContext abilityContext;

New Construction

If you want to experience the tool's ability to generate template code, you can use DevEco Studio to create a simple mobile phone project including a JS front end, and use it to develop a simple FA calling PA application.

Tool switches and compile settings

Control the switch and compile settings in build.gradle under the module that needs to generate code. If you want to quickly verify the function, you can choose to modify the build.gradle of the entry module and verify it through the entry module.

The compilation parameters are located in ohos -> defaultConfig, just add the following settings. Developers need to set the JS template code generation path here, which is the value corresponding to 'jsOutputDir'.

// 在文件头部定义JS模板代码生成路径
def jsOutputDir = project.file("src/main/js/default/generated").toString()
 
// 在ohos -> defaultConfig中设置JS模板代码生成路径
javaCompileOptions {
    annotationProcessorOptions {
        arguments = ["jsOutputDir": jsOutputDir] // JS模板代码生成赋值
    }
}

The tool switch is in ohos, just add the settings like below. A value of true enables the tool, false or no configuration does not enable the tool.

compileOptions {
    f2pautogenEnabled true // 此处为启用js2java-codegen工具的开关
}

Java side code writing

The generation of the template code requires the developer to provide the PA for FA calls, so the developer needs to write the InternalAbility class by himself, and then add the @InternalAbility annotation to the class, and set the registerTo parameter to the full name of the Ability class to be registered. (The Ability class can use the existing MainAbility class in the project, or create a new Ability class)

Note that the method in the InternalAbility class that needs to be exposed to FA to call can only be a public type non-static non-void method, otherwise it will not be exposed.

A simple InternalAbility class is implemented as follows. The file name is Service.java, which is in the same package as the MainAbility class, and registered to the MainAbility class with annotations. The class contains an add method as an ability exposed to JS FA to call, which realizes the function of adding two numbers. The input parameter is two int parameters, and the return value is the sum of the two numbers.

package com.example.myapplication;

import ohos.annotation.f2pautogen.InternalAbility;

@InternalAbility(registerTo = "com.example.myapplication.MainAbility") // 此处registerTo的参数为项目中MainAbility类的全称
public class Service {
    public int add(int num1, int num2) {
        return num1 + num2;
    }
}

compile

The js2java-codegen tool will be automatically called during the compilation process to automatically generate template code and complete the entire channel establishment process.

Click Build -> Build HAP(s)/APP(s) -> Build HAP(s) in the menu bar to complete the compilation of the project, and the js2java-codegen tool will complete the FA calling of the PA channel during the compilation process Establish.

The compilation process generates template code for Java and JS. The JS template code is located in the path set by the developer in the compilation settings, and the name corresponds to the name of the InternalAbility class; while the Java template code is located in entry > build > generated > source > annotation > debug > InternalAbility class with the same name package > InternalAbility class Name+Stub.java , and the call statement of this class will be injected into the bytecode of the MainAbility class. The following two figures are examples of the generated template code.

Java template code example

 JS template code example

JS side code writing

In order to check the usability of the code generated by the tool simply and intuitively, developers can call the capabilities on the Java side by modifying entry > src > main > js > default > pages > index > index.js and display the effect on the front-end page.

The FA interface on the JS side can be introduced through import, such as import Service from '../../generated/Service.js' ; (the value after from needs to be unified with the path in the compilation settings. The generated JS code file name and The class name is the same as the InternalAbility class name.)

A simple index.js page is implemented as follows, calling the JS side interface, passing in two parameters of 1 and 10, and printing the returned result in the title, so that as long as the application is run, it can be verified whether FA calls PA successfully.

import Service from '../../generated/Service.js'; // 此处FA路径和类名对应之前的jsOutput路径以及InternalAbility的名字
export default {
    data: {
        title: "Result:"
    },
    onInit() {
        const echo = new Service(); // 此处新建FA实例
        echo.add(1,10)
            .then((data) => {
            this.title += data["abilityResult"]; // 此处取到运算结果,并加到title之后
        });
    }
}

In order to facilitate the display of the results, here is also a little modification to the index.hml in the same directory, so that only the content of the title is displayed on the page.

<div class="container">
    <text class="title">
        {
   
   { title }}
    </text>
</div>

Result verification

Start the mobile phone emulator, and run the application after the startup is successful. If you see the following display, it means that the js2java-codegen tool has generated effective template code and successfully established the channel for FA to call PA.

Simulator verification effect

Guess you like

Origin blog.csdn.net/weixin_47094733/article/details/131249835