source
stringlengths
14
113
code
stringlengths
10
21.3k
application-dev\arkts-utils\arkts-sendable-module.md
// side-effects-import is not allowed. import "./sharedModule";
application-dev\arkts-utils\arkts-sendable-module.md
// test.ets export let num = 1; export let str = 'aaa';
application-dev\arkts-utils\arkts-sendable-module.md
// share.ets // Shared module 'use shared' export * from './test'; // A compile-time error is reported. The module cannot be directly exported. export {num, str} from './test'; // Correct example. Export the object set.
application-dev\arkts-utils\arkts-sendable-module.md
// test.ets import { num } from './A'; // Static loading is supported. import worker from '@ohos.worker'; let wk = new worker.ThreadWorker("./A"); // Other methods of loading shared modules are not supported and will result in runtime errors. // A.ets 'use shared' export {num, str} from './test';
application-dev\arkts-utils\arkts-sendable-module.md
// Shared module sharedModule.ets import { ArkTSUtils } from '@kit.ArkTS'; // Declare the current module as shared. Only Sendable data can be exported. "use shared" // Shared module. SingletonA is globally unique. @Sendable class SingletonA { private count_: number = 0; lock_: ArkTSU...
application-dev\arkts-utils\arkts-sendable-module.md
import { taskpool } from '@kit.ArkTS'; import { singletonA } from './sharedModule'; @Concurrent async function increaseCount() { await singletonA.increaseCount(); console.info("SharedModule: count is:" + await singletonA.getCount()); } @Concurrent async function printCount() { c...
application-dev\arkts-utils\arkts-sendable.md
@Sendable class SendableTestClass { desc: string = "sendable: this is SendableTestClass "; num: number = 5; printName() { console.info("sendable: SendableTestClass desc is: " + this.desc); } get getNum(): number { return this.num; } }
application-dev\arkts-utils\arkts-sendable.md
@Sendable type SendableFuncType = () => void; @Sendable class TopLevelSendableClass { num: number = 1; PrintNum() { console.info("Top level sendable class"); } } @Sendable function TopLevelSendableFunction() { console.info("Top level sendable function"); } @Sendable function SendableTestFunction() { co...
application-dev\arkts-utils\arraybuffer-object.md
// Index.ets import { taskpool } from '@kit.ArkTS'; import { BusinessError } from '@kit.BasicServicesKit'; @Concurrent function adjustImageValue(arrayBuffer: ArrayBuffer): ArrayBuffer { // Perform operations on the ArrayBuffer. return arrayBuffer; // The return value is passed by transfer by default. } function ...
application-dev\arkts-utils\ason-parsing-generation.md
import { ArkTSUtils, collections } from '@kit.ArkTS'; ArkTSUtils.ASON.parse("{}") ArkTSUtils.ASON.stringify(new collections.Array(1, 2, 3)) let options2: ArkTSUtils.ASON.ParseOptions = { bigIntMode: ArkTSUtils.ASON.BigIntMode.PARSE_AS_BIGINT, parseReturnType: ArkTSUtils.ASON.ParseReturnType.MAP, } let jsonTex...
application-dev\arkts-utils\async-concurrency-overview.md
const promise: Promise<number> = new Promise((resolve: Function, reject: Function) => { setTimeout(() => { const randomNumber: number = Math.random(); if (randomNumber > 0.5) { resolve(randomNumber); } else { reject(new Error('Random number is too small')); } }, 1000); })
application-dev\arkts-utils\async-concurrency-overview.md
import { BusinessError } from '@kit.BasicServicesKit'; // Use the then method to define success and failure callbacks. promise.then((result: number) => { console.info(`The number for success is ${result}`); // Executed on success. }, (error: BusinessError) => { console.error(error.message); // Executed on failure....
application-dev\arkts-utils\async-concurrency-overview.md
async function myAsyncFunction(): Promise<string> { const result: string = await new Promise((resolve: Function) => { setTimeout(() => { resolve('Hello, world!'); }, 3000); }); console.info(result); // Output: Hello, world! return result; } @Entry @Component struct Index { @State message: strin...
application-dev\arkts-utils\async-concurrency-overview.md
async function myAsyncFunction(): Promise<void> { try { const result: string = await new Promise((resolve: Function) => { resolve('Hello, world!'); }); } catch (e) { console.error(`Get exception: ${e}`); } } myAsyncFunction();
application-dev\arkts-utils\batch-database-operations-guide.md
// Index.ets import { relationalStore, ValuesBucket } from '@kit.ArkData'; import { taskpool } from '@kit.ArkTS'; @Concurrent async function create(context: Context) { const CONFIG: relationalStore.StoreConfig = { name: "Store.db", securityLevel: relationalStore.SecurityLevel.S1, }; // The default datab...
application-dev\arkts-utils\batch-database-operations-guide.md
// SharedValuesBucket.ets export interface IValueBucket { id: number name: string age: number salary: number } @Sendable export class SharedValuesBucket implements IValueBucket { id: number = 0 name: string = "" age: number = 0 salary: number = 0 construc...
application-dev\arkts-utils\batch-database-operations-guide.md
// Index.ets import { relationalStore, ValuesBucket } from '@kit.ArkData'; import { collections, taskpool } from '@kit.ArkTS'; import { IValueBucket, SharedValuesBucket } from './SharedValuesBucket'; @Concurrent async function create(context: Context) { const CONFIG: relationalStore.StoreConfig ...
application-dev\arkts-utils\batch-database-operations-guide.md
// SharedValuesBucket.ets export interface IValueBucket { id: number; name: string; age: number; salary: number; } @Sendable export class SharedValuesBucket implements IValueBucket { id: number = 0; name: string = ""; age: number = 0; salary: number = 0; ...
application-dev\arkts-utils\batch-database-operations-guide.md
// Material.ets import { SharedValuesBucket } from './SharedValuesBucket'; import { collections } from '@kit.ArkTS'; export class Material { seq: number = 0; materialName: string = ""; //... Other properties are omitted. buckets: collections.Array<SharedValuesBucket | undefined>; con...
application-dev\arkts-utils\batch-database-operations-guide.md
// Index.ets import { relationalStore, ValuesBucket } from '@kit.ArkData'; import { collections, taskpool } from '@kit.ArkTS'; import { IValueBucket, SharedValuesBucket } from './SharedValuesBucket'; import { Material } from './Material'; @Concurrent async function create(context: Context) { con...
application-dev\arkts-utils\bytecode-obfuscation-guide.md
// Static definition, dynamic access: The property name is static during object definition, but is accessed by dynamically constructing the property name (usually using string concatenation). const obj = { staticName: value // Static definition }; const fieldName = 'static' + 'Name'; /...
application-dev\arkts-utils\bytecode-obfuscation-guide.md
// Dynamic definition, static access: The property name is determined during object definition through a dynamic expression, but is statically accessed using dot notation (assuming that you know the result of the property name). const obj = { [dynamicExpression]: value // Dynamic definition }; ...
application-dev\arkts-utils\bytecode-obfuscation-questions.md
@Component export struct MainPage { @State messageStr: string = 'Hello World'; ... }
application-dev\arkts-utils\bytecode-obfuscation-questions.md
class Info { @Trace sample: Sample = new Sample(); }
application-dev\arkts-utils\bytecode-obfuscation-questions.md
// Code 1 @CustomDialog export default struct TmsDialog { controller?: CustomDialogController dialogController:CustomDialogController; } // Code 2 @CustomDialog struct Index{ controller?: CustomDialogController dialogController?:CustomDialogController }
application-dev\arkts-utils\bytecode-obfuscation-questions.md
dialogController:CustomDialogController|null = null;
application-dev\arkts-utils\bytecode-obfuscation-questions.md
// Before obfuscation: const jsonData = ('./1.json') let jsonStr = JSON.parse(jsonData) let jsonObj = jsonStr.jsonProperty // After obfuscation: const jsonData = ('./1.json') let jsonStr = JSON.parse(jsonData) let jsonObj = jsonStr.i
application-dev\arkts-utils\bytecode-obfuscation-questions.md
// Before obfuscation: import { Want } from '@kit.AbilityKit'; let petalMapWant: Want = { bundleName: 'com.example.myapplication', uri: 'maps://', parameters: { linkSource: 'com.other.app' } } // After obfuscation: import type Want from "@ohos:app.ability.Want"; let petalMapWant: Want = { bundleName: 'c...
application-dev\arkts-utils\bytecode-obfuscation-questions.md
@ObservedV2 class SampleChild { @Trace p123: number = 0; p2: number = 10; } @ObservedV2 export class Sample { // For complex objects, use the @Type decorator to ensure successful serialization. @Type(SampleChild) @Trace f123: SampleChild = new SampleChild(); } // Call the API. this.prop = PersistenceV2.conne...
application-dev\arkts-utils\bytecode-obfuscation-questions.md
// Before obfuscation: // file1.ts export interface MyInfo { age: number; address: { city1: string; } } // file2.ts import { MyInfo } from './file1'; const person: MyInfo = { age: 20, address: { city1: "shanghai" } } // After obfuscation, the code of file1.ts is retained. // file2.ts import { MyInfo...
application-dev\arkts-utils\bytecode-obfuscation-questions.md
// file1.ts export interface AddressType { city1: string } export interface MyInfo { age: number; address: AddressType; }
application-dev\arkts-utils\bytecode-obfuscation-questions.md
-keep-property-name city1
application-dev\arkts-utils\bytecode-obfuscation-questions.md
// Before obfuscation: export class Test1 {} let mytest = (await import('./file')).Test1 // After obfuscation: export class w1 {} let mytest = (await import('./file')).Test1
application-dev\arkts-utils\bytecode-obfuscation-questions.md
// Before obfuscation: export namespace ns1 { export class person1 {} } import {ns1} from './file1' let person1 = new ns1.person1() // After obfuscation: export namespace a3 { export class b2 {} } import {a3} from './file1' let person1 = new a3.person1()
application-dev\arkts-utils\bytecode-obfuscation-questions.md
// Before obfuscation: declare global { var age : string } // After obfuscation: declare a2 { var b2 : string }
application-dev\arkts-utils\bytecode-obfuscation-questions.md
person["personAge"] = 22; // Before obfuscation person["b"] = 22; // After obfuscation
application-dev\arkts-utils\bytecode-obfuscation.md
// Before obfuscation: class TestA { static prop1: number = 0; } TestA.prop1;
application-dev\arkts-utils\bytecode-obfuscation.md
// After obfuscation: class TestA { static i: number = 0; } TestA.i;
application-dev\arkts-utils\bytecode-obfuscation.md
export class MyClass { data: string; }
application-dev\arkts-utils\bytecode-obfuscation.md
@Component struct MyExample { @State message: string = "hello"; data: number[] = []; // ... }
application-dev\arkts-utils\bytecode-obfuscation.md
let person = {"firstName": "abc"}; person["personAge"] = 22;
application-dev\arkts-utils\bytecode-obfuscation.md
@interface MyAnnotation { authorName: string; revision: number = 1; }
application-dev\arkts-utils\bytecode-obfuscation.md
// Before obfuscation: let person = {"fritstName": "abc"}; person["personAge"] = 22;
application-dev\arkts-utils\bytecode-obfuscation.md
// After obfuscation: let person = {"a": "abc"}; person["b"] = 22;
application-dev\arkts-utils\bytecode-obfuscation.md
// Part of the SDK API file @ohos.app.ability.wantConstant: export enum Params { ACTION_HOME = 'ohos.want.action.home' } // Source code example: let params = obj['ohos.want.action.home'];
application-dev\arkts-utils\bytecode-obfuscation.md
// Before obfuscation: let count = 0;
application-dev\arkts-utils\bytecode-obfuscation.md
// After obfuscation: let s = 0;
application-dev\arkts-utils\bytecode-obfuscation.md
// Before obfuscation: namespace ns { export type customT = string; }
application-dev\arkts-utils\bytecode-obfuscation.md
// After obfuscation: namespace ns { export type h = string; }
application-dev\arkts-utils\bytecode-obfuscation.md
// Before obfuscation: import * as m from '../test1/test2'; import { foo } from '../test1/test2'; const module = import('../test1/test2');
application-dev\arkts-utils\bytecode-obfuscation.md
// After obfuscation: import * as m from '../a/b'; import { foo } from '../a/b'; const module = import('../a/b');
application-dev\arkts-utils\bytecode-obfuscation.md
// Before obfuscation: class TestA { static prop1: number = 0; } TestA.prop1;
application-dev\arkts-utils\bytecode-obfuscation.md
// After obfuscation: class TestA { static prop1: number = 0; } TestA.prop1;
application-dev\arkts-utils\bytecode-obfuscation.md
// Before obfuscation: if (flag) { console.log("hello"); }
application-dev\arkts-utils\bytecode-obfuscation.md
// After obfuscation: if (flag) { }
application-dev\arkts-utils\bytecode-obfuscation.md
function foo() { console.log('in block'); }
application-dev\arkts-utils\bytecode-obfuscation.md
namespace ns { console.log('in ns'); }
application-dev\arkts-utils\bytecode-obfuscation.md
export class MyClass { person = {firstName: "123", personAge: 100}; }
application-dev\arkts-utils\bytecode-obfuscation.md
import testNapi from 'library.so' testNapi.foo() // foo should be retained Example: -keep-property-name foo
application-dev\arkts-utils\bytecode-obfuscation.md
// Example JSON file structure (test.json): /* { "jsonProperty": "value", "otherProperty": "value2" } */ const jsonData = fs.readFileSync('./test.json', 'utf8'); let jsonObj = JSON.parse(jsonData); let jsonProp = jsonObj.jsonProperty; // jsonProperty should be retained. class jsonTest ...
application-dev\arkts-utils\bytecode-obfuscation.md
const valueBucket: ValuesBucket = { 'ID1': ID1, // ID1 should be retained. 'NAME1': name, // NAME1 should be retained. 'AGE1': age, // AGE1 should be retained. 'SALARY1': salary // SALARY1 should be retained. }
application-dev\arkts-utils\bytecode-obfuscation.md
class A { // 1. Member variable decorator @CustomDecoarter propertyName: string = "" // propertyName should be retained. // 2. Member method decorator @MethodDecoarter methodName1(){} // methodName1 should be retained. // 3. Method parameter decorator me...
application-dev\arkts-utils\bytecode-obfuscation.md
export namespace Ns { export const age = 18; // -keep-global-name age: retains variable age. export function myFunc () {}; // -keep-global-name myFunc: retains function myFunc. }
application-dev\arkts-utils\bytecode-obfuscation.md
var a = 0; console.info(globalThis.a); // a should be retained. function foo(){} globalThis.foo(); // foo should be retained. var c = 0; console.info(c); // c can be correctly obfuscated. function bar(){} bar(); // bar can be correctly obfuscated. clas...
application-dev\arkts-utils\bytecode-obfuscation.md
import { testNapi, testNapi1 as myNapi } from 'library.so' // testNapi and testNapi1 should be retained.
application-dev\arkts-utils\bytecode-obfuscation.md
const module1 = require('./file1') // file1 should be retained.
application-dev\arkts-utils\bytecode-obfuscation.md
const moduleName = './file2' // The path name file2 corresponding to moduleName should be retained. const module2 = import(moduleName)
application-dev\arkts-utils\concurrency-faq.md
console.log("test start"); ... // Other service logic. taskpool.execute(xxx); // If "test start" is printed in the console but the Task Allocation: taskId: log is missing, taskpool.execute is not executed. Check the preceding service logic.
application-dev\arkts-utils\concurrency-faq.md
// HiLog log snippet (simulation) // Log 1: A large number of tasks are submitted. taskpool:: Task Allocation: taskId: , priority: , executeState: taskpool:: Task Allocation: taskId: , priority: , executeState: taskpool:: Task Allocation: taskId: , priority: , executeState: taskpool:: Task Allocation: ta...
application-dev\arkts-utils\concurrency-faq.md
taskpool.execute().then((res: object)=>{ // Handle the result after task execution. ... }).catch((e: Error)=>{ // Handle the exception after task failure. ... })
application-dev\arkts-utils\concurrency-faq.md
// HiLog log snippet 1 (simulation) // seqRunner has four tasks. taskpool:: taskId 389508780288 in seqRunnner 393913878464 immediately. taskpool:: add taskId: 394062838784 to seqRunnner 393913878464 taskpool:: add taskId: 393918679936 to seqRunnner 393913878464 taskpool:: add taskId: 393918673408 to seqRunnner 39391387...
application-dev\arkts-utils\concurrency-faq.md
Error message:An exception occurred during serialization, taskpool: failed to serialize arguments.
application-dev\arkts-utils\concurrency-faq.md
[ecmascript] Unsupport serialize object type: [ecmascript] ValueSerialize: serialize data is incomplete
application-dev\arkts-utils\concurrency-faq.md
// pages/index.ets import { worker, ErrorEvent } from '@kit.ArkTS' import { A } from './sendable' const workerInstance = new worker.ThreadWorker('../workers/Worker.ets'); function testInstanceof() { let a = new A(); if (a instanceof A) { // Print "test instanceof in main thread success". console.log("test i...
application-dev\arkts-utils\concurrency-faq.md
// pages/sendable.ets "use shared" @Sendable export class A { name: string = "name"; printName(): string { return this.name; } }
application-dev\arkts-utils\concurrency-faq.md
// workers/Worker.ets import { A } from '../pages/sendable' import { worker, ThreadWorkerGlobalScope, MessageEvents } from '@kit.ArkTS' const workerPort: ThreadWorkerGlobalScope = worker.workerPort; workerPort.onmessage = (e: MessageEvents) => { let a : A = e.data as A; if (a instanceof A) { // Print "...
application-dev\arkts-utils\concurrency-faq.md
JavaScript exception: TypeError: Cannot set sendable property with mismatched type
application-dev\arkts-utils\concurrency-faq.md
@Sendable export class B { constructor() {} } @Sendable export class A { constructor(b: B) { this.b = b; } public b: B | undefined = undefined; }
application-dev\arkts-utils\concurrency-faq.md
JavaScript exception: TypeError: Cannot add property in prevent extensions
application-dev\arkts-utils\concurrent-loading-modules-guide.md
// sdk/Calculator.ets import { collections } from '@kit.ArkTS' @Sendable export class Calculator { history?: collections.Array<collections.Array<string>> totalCount: number = 0 static init(): Calculator { let calc = new Calculator() calc.totalCount = 0 calc.history =...
application-dev\arkts-utils\concurrent-loading-modules-guide.md
// sdk/TimerSdk.ets @Sendable export class TimerSdk { static init(): TimerSdk { let timer = new TimerSdk() return timer } async Countdown(time: number) { return new Promise((resolve: (value: boolean) => void) => { setTimeout(() => { resolve(true) ...
application-dev\arkts-utils\concurrent-loading-modules-guide.md
// Index.ets import { Calculator } from '../sdk/Calculator' import { TimerSdk } from '../sdk/TimerSdk' import { taskpool } from '@kit.ArkTS'; @Concurrent function initCalculator(): Calculator { return Calculator.init() } @Concurrent function initTimerSdk(): TimerSdk { return Ti...
application-dev\arkts-utils\cpu-intensive-task-development.md
import { taskpool } from '@kit.ArkTS'; @Concurrent function imageProcessing(dataSlice: ArrayBuffer): ArrayBuffer { // Step 1: Perform specific image processing operations and other time-consuming operations. return dataSlice; } function histogramStatistic(pixelBuffer: ArrayBuffer): void { // Step 2: Segment the...
application-dev\arkts-utils\cpu-intensive-task-development.md
// Index.ets import { worker } from '@kit.ArkTS'; const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ets');
application-dev\arkts-utils\cpu-intensive-task-development.md
// Index.ets let done = false; // Receive results from the Worker thread. workerInstance.onmessage = (() => { console.info('MyWorker.ets onmessage'); if (!done) { workerInstance.postMessage({ 'type': 1, 'value': 0 }); done = true; } }) workerInstance.onAllErrors =...
application-dev\arkts-utils\cpu-intensive-task-development.md
// MyWorker.ets import { worker, ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@kit.ArkTS'; let workerPort: ThreadWorkerGlobalScope = worker.workerPort;
application-dev\arkts-utils\cpu-intensive-task-development.md
// MyWorker.ets // Define the training model and results. let result: Array<number>; // Define the prediction function. function predict(x: number): number { return result[x]; } // Define the optimizer training process. function optimize(): void { result = [0]; } // onmessa...
application-dev\arkts-utils\cpu-intensive-task-development.md
// Index.ets // After the Worker thread is destroyed, execute the onexit callback. workerInstance.onexit = (): void => { console.info("main thread terminate"); }
application-dev\arkts-utils\cpu-intensive-task-development.md
// Index.ets // Destroy the Worker thread. workerInstance.terminate();
application-dev\arkts-utils\cpu-intensive-task-development.md
// MyWorker.ets // Destroy the Worker thread. workerPort.close();
application-dev\arkts-utils\gc-introduction.md
// Declare the interface first. declare class ArkTools { static hintGC(): void; } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) Button("Trigger Hint GC").onCl...
application-dev\arkts-utils\global-configuration-guide.md
// Config.ets import { ArkTSUtils } from '@kit.ArkTS'; "use shared" @Sendable class Config { lock: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock isLogin: boolean = false; loginUser?: string; wifiOn: boolean = false async login(user: string) { ret...
application-dev\arkts-utils\global-configuration-guide.md
import { config } from './Config' import { taskpool } from '@kit.ArkTS'; @Concurrent async function download() { if (!await config.isWifiOn()) { console.info("wifi is off") return false; } if (!await config.getIsLogin()) { console.info("not login") return false; ...
application-dev\arkts-utils\independent-time-consuming-task.md
// IconItemSource.ets export class IconItemSource { image: string | Resource = ''; text: string | Resource = ''; constructor(image: string | Resource = '', text: string | Resource = '') { this.image = image; this.text = text; } }
application-dev\arkts-utils\independent-time-consuming-task.md
// IndependentTask.ets import { IconItemSource } from './IconItemSource'; // Methods executed in the TaskPool thread must be decorated by @Concurrent. Otherwise, they cannot be called. @Concurrent export function loadPicture(count: number): IconItemSource[] { let iconItemSourceList: IconItemSource...
application-dev\arkts-utils\independent-time-consuming-task.md
// Index.ets import { taskpool } from '@kit.ArkTS'; import { IconItemSource } from './IconItemSource'; import { loadPicture } from './IndependentTask'; @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Tex...
application-dev\arkts-utils\io-intensive-task-development.md
// write.ets import { fileIo } from '@kit.CoreFileKit' // Define a concurrent function that frequently calls I/O operations. // Write data to the file. export async function write(data: string, filePath: string): Promise<void> { let file: fileIo.File = await fileIo.open(filePath, fileIo.OpenMode....
application-dev\arkts-utils\io-intensive-task-development.md
// Index.ets import { write } from './write' import { BusinessError } from '@kit.BasicServicesKit'; import { taskpool } from '@kit.ArkTS'; import { common } from '@kit.AbilityKit'; @Concurrent async function concurrentTest(context: common.UIAbilityContext): Promise<boolean> { let filePath...
application-dev\arkts-utils\io-intensive-task-development.md
// Index.ets @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { let context = ...
application-dev\arkts-utils\linear-container.md
// ArrayList import { ArrayList } from '@kit.ArkTS'; // Import the ArrayList module. let arrayList1: ArrayList<string> = new ArrayList(); arrayList1.add('a'); // Add an element with the value 'a'. let arrayList2: ArrayList<number> = new ArrayList(); arrayList2.add(1); // Add an element with the value 1. console.info(`...