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_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock()
public async getCount(): Promise<number> {
return this.lock_.lockAsync(() => {
return this.count_;
})
}
public async increaseCount() {
await this.lock_.lockAsync(() => {
this.count_++;
})
}
}
export let singletonA = new SingletonA(); |
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() {
console.info("SharedModule: count is:" + await singletonA.getCount());
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Button("MainThread print count")
.onClick(async () => {
await printCount();
})
Button("Taskpool print count")
.onClick(async () => {
await taskpool.execute(printCount);
})
Button("MainThread increase count")
.onClick(async () => {
await increaseCount();
})
Button("Taskpool increase count")
.onClick(async () => {
await taskpool.execute(increaseCount);
})
}
.width('100%')
}
.height('100%')
}
} |
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() {
const topClass = new TopLevelSendableClass(); // Top-level Sendable class.
topClass.PrintNum();
TopLevelSendableFunction(); // Top-level Sendable function.
console.info("Sendable test function");
}
@Sendable
class SendableTestClass {
constructor(func: SendableFuncType) {
this.callback = func;
}
callback: SendableFuncType; // Top-level Sendable function.
CallSendableFunc() {
SendableTestFunction(); // Top-level Sendable function.
}
}
let sendableClass = new SendableTestClass(SendableTestFunction);
sendableClass.callback();
sendableClass.CallSendableFunc(); |
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 createImageTask(arrayBuffer: ArrayBuffer, isParamsByTransfer: boolean): taskpool.Task {
let task: taskpool.Task = new taskpool.Task(adjustImageValue, arrayBuffer);
if (!isParamsByTransfer) { // Whether to use pass-by-transfer.
// Pass an empty array [] to indicate that all ArrayBuffer parameters should be passed by copy.
task.setTransferList([]);
}
return task;
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
let taskNum = 4;
let arrayBuffer = new ArrayBuffer(1024 * 1024);
let taskPoolGroup = new taskpool.TaskGroup();
// Create taskNum tasks.
for (let i: number = 0; i < taskNum; i++) {
let arrayBufferSlice: ArrayBuffer = arrayBuffer.slice(arrayBuffer.byteLength / taskNum * i, arrayBuffer.byteLength / taskNum * (i + 1));
// To pass the ArrayBuffer object by copy, set isParamsByTransfer to false.
taskPoolGroup.addTask(createImageTask(arrayBufferSlice, false));
}
// Execute the tasks.
taskpool.execute(taskPoolGroup).then((data) => {
// Concatenate the results to obtain the final result.
}).catch((e: BusinessError) => {
console.error(e.message);
})
})
}
.height('100%')
.width('100%')
}
} |
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 jsonText = '{"largeNumber":112233445566778899}';
let map = ArkTSUtils.ASON.parse(jsonText, undefined, options2);
ArkTSUtils.ASON.stringify(map); |
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.
}
);
// Use the then method to define a success callback and the catch method to define a failure callback.
promise.then((result: number) => {
console.info(`Random number is ${result}`); // Executed on success.
}).catch((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: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(async () => {
let res = await myAsyncFunction();
console.info('res is: ' + res);
})
}
.width('100%')
}
.height('100%')
}
} |
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 database file path is context.databaseDir + rdb + StoreConfig.name.
let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
console.info(`Create Store.db successfully!`);
// Create a table.
const CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS test (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT NOT NULL, " +
"age INTEGER, " +
"salary REAL, " +
"blobType BLOB)";
await store.executeSql(CREATE_TABLE_SQL);
console.info(`Create table test successfully!`);
}
@Concurrent
async function insert(context: Context, valueBucketArray: Array<relationalStore.ValuesBucket>) {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
console.info(`Create Store.db successfully!`);
// Insert data.
await store.batchInsert("test", valueBucketArray as Object as Array<relationalStore.ValuesBucket>);
}
@Concurrent
async function query(context: Context): Promise<Array<relationalStore.ValuesBucket>> {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
console.info(`Create Store.db successfully!`);
// Obtain the result set.
let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates("test");
let resultSet = await store.query(predicates); // Query all data.
console.info(`Query data successfully! row count:${resultSet.rowCount}`);
let index = 0;
let result = new Array<relationalStore.ValuesBucket>(resultSet.rowCount)
resultSet.goToFirstRow()
do {
result[index++] = resultSet.getRow()
} while (resultSet.goToNextRow());
resultSet.close();
return result
}
@Concurrent
async function clear(context: Context) {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
await relationalStore.deleteRdbStore(context, CONFIG);
console.info(`Delete Store.db successfully!`);
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
let context : Context = this.getUIContext().getHostContext() as Context;
// Prepare data.
const count = 5
let valueBucketArray = new Array<relationalStore.ValuesBucket>(count);
for (let i = 0; i < count; i++) {
let v : relationalStore.ValuesBucket = {
id: i,
name: "zhangsan" + i,
age: 20,
salary: 5000 + 50 * i
};
valueBucketArray[i] = v;
}
await taskpool.execute(create, context)
await taskpool.execute(insert, context, valueBucketArray)
let index = 0
let ret = await taskpool.execute(query, context) as Array<relationalStore.ValuesBucket>
for (let v of ret) {
console.info(`Row[${index}].id = ${v.id}`)
console.info(`Row[${index}].name = ${v.name}`)
console.info(`Row[${index}].age = ${v.age}`)
console.info(`Row[${index}].salary = ${v.salary}`)
index++
}
await taskpool.execute(clear, context)
})
}
.height('100%')
.width('100%')
}
} |
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
constructor(v: IValueBucket) {
this.id = v.id;
this.name = v.name;
this.age = v.age;
this.salary = v.salary
}
} |
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 = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
console.info(`Create Store.db successfully!`);
// Create a table.
const CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS test (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT NOT NULL, " +
"age INTEGER, " +
"salary REAL, " +
"blobType BLOB)";
await store.executeSql(CREATE_TABLE_SQL);
console.info(`Create table test successfully!`);
}
@Concurrent
async function insert(context: Context, valueBucketArray: collections.Array<SharedValuesBucket | undefined>) {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
console.info(`Create Store.db successfully!`);
// Insert data.
await store.batchInsert("test", valueBucketArray as Object as Array<ValuesBucket>);
}
@Concurrent
async function query(context: Context): Promise<collections.Array<SharedValuesBucket | undefined>> {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
console.info(`Create Store.db successfully!`);
// Obtain the result set.
let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates("test");
let resultSet = await store.query(predicates); // Query all data.
console.info(`Query data successfully! row count:${resultSet.rowCount}`);
let index = 0;
let result = collections.Array.create<SharedValuesBucket | undefined>(resultSet.rowCount, undefined)
resultSet.goToFirstRow()
do {
let v: IValueBucket = {
id: resultSet.getLong(resultSet.getColumnIndex("id")),
name: resultSet.getString(resultSet.getColumnIndex("name")),
age: resultSet.getLong(resultSet.getColumnIndex("age")),
salary: resultSet.getLong(resultSet.getColumnIndex("salary"))
};
result[index++] = new SharedValuesBucket(v)
} while (resultSet.goToNextRow());
resultSet.close();
return result
}
@Concurrent
async function clear(context: Context) {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
await relationalStore.deleteRdbStore(context, CONFIG);
console.info(`Delete Store.db successfully!`);
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
let context : Context = this.getUIContext().getHostContext() as Context;
// Prepare data.
const count = 5
let valueBucketArray = collections.Array.create<SharedValuesBucket | undefined>(count, undefined);
for (let i = 0; i < count; i++) {
let v: IValueBucket = {
id: i,
name: "zhangsan" + i,
age: 20,
salary: 5000 + 50 * i
};
valueBucketArray[i] = new SharedValuesBucket(v);
}
await taskpool.execute(create, context)
await taskpool.execute(insert, context, valueBucketArray)
let index = 0
let ret: collections.Array<SharedValuesBucket> =
await taskpool.execute(query, context) as collections.Array<SharedValuesBucket>
for (let v of ret.values()) {
console.info(`Row[${index}].id = ${v.id}`)
console.info(`Row[${index}].name = ${v.name}`)
console.info(`Row[${index}].age = ${v.age}`)
console.info(`Row[${index}].salary = ${v.salary}`)
index++
}
await taskpool.execute(clear, context)
})
}
.height('100%')
.width('100%')
}
} |
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;
constructor(v: IValueBucket) {
this.id = v.id;
this.name = v.name;
this.age = v.age;
this.salary = v.salary;
}
} |
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>;
constructor(seq: number, materialName: string, buckets: collections.Array<SharedValuesBucket | undefined>) {
this.seq = seq;
this.materialName = materialName;
this.buckets = buckets;
}
getBuckets() : collections.Array<SharedValuesBucket | undefined>{
return this.buckets;
}
setBuckets(buckets: collections.Array<SharedValuesBucket | undefined>) {
this.buckets = buckets;
}
} |
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) {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
console.info(`Create Store.db successfully!`);
// Create a table.
const CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS test (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT NOT NULL, " +
"age INTEGER, " +
"salary REAL, " +
"blobType BLOB)";
await store.executeSql(CREATE_TABLE_SQL);
console.info(`Create table test successfully!`);
}
@Concurrent
async function insert(context: Context, valueBucketArray: collections.Array<SharedValuesBucket | undefined>) {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
console.info(`Create Store.db successfully!`);
// Insert data.
await store.batchInsert("test", valueBucketArray as Object as Array<ValuesBucket>);
}
@Concurrent
async function query(context: Context): Promise<collections.Array<SharedValuesBucket | undefined>> {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG);
console.info(`Create Store.db successfully!`);
// Obtain the result set.
let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates("test");
let resultSet = await store.query(predicates); // Query all data.
console.info(`Query data successfully! row count:${resultSet.rowCount}`);
let index = 0;
let result = collections.Array.create<SharedValuesBucket | undefined>(resultSet.rowCount, undefined)
resultSet.goToFirstRow()
do {
let v: IValueBucket = {
id: resultSet.getLong(resultSet.getColumnIndex("id")),
name: resultSet.getString(resultSet.getColumnIndex("name")),
age: resultSet.getLong(resultSet.getColumnIndex("age")),
salary: resultSet.getLong(resultSet.getColumnIndex("salary"))
};
result[index++] = new SharedValuesBucket(v)
} while (resultSet.goToNextRow());
resultSet.close();
return result
}
@Concurrent
async function clear(context: Context) {
const CONFIG: relationalStore.StoreConfig = {
name: "Store.db",
securityLevel: relationalStore.SecurityLevel.S1,
};
// The default database file path is context.databaseDir + rdb + StoreConfig.name.
await relationalStore.deleteRdbStore(context, CONFIG);
console.info(`Delete Store.db successfully!`);
}
function initMaterial() : Material {
// Prepare data.
const count = 5
let valueBucketArray = collections.Array.create<SharedValuesBucket | undefined>(count, undefined);
for (let i = 0; i < count; i++) {
let v: IValueBucket = {
id: i,
name: "zhangsan" + i,
age: 20,
salary: 5000 + 50 * i
};
valueBucketArray[i] = new SharedValuesBucket(v);
}
let material = new Material(1, "test", valueBucketArray);
return material;
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
let context : Context = this.getUIContext().getHostContext() as Context;
let material = initMaterial();
await taskpool.execute(create, context);
await taskpool.execute(insert, context, material.getBuckets());
let index = 0;
let ret: collections.Array<SharedValuesBucket> =
await taskpool.execute(query, context) as collections.Array<SharedValuesBucket>;
material.setBuckets(ret);
for (let v of ret.values()) {
console.info(`Row[${index}].id = ${v.id}`);
console.info(`Row[${index}].name = ${v.name}`);
console.info(`Row[${index}].age = ${v.age}`);
console.info(`Row[${index}].salary = ${v.salary}`);
index++;
}
await taskpool.execute(clear, context);
})
}
.height('100%')
.width('100%')
}
} |
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'; // Dynamic construction of the property name
console.log(obj[fieldName]); // Use square bracket notation to dynamically access the property. |
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
};
console.log(obj.dynamicPropertyName); // Use dot notation to statically access the property. |
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: 'com.example.myapplication',
uri: 'maps://',
parameters: {
i: 'com.other.app'
}
}; |
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.connect(Sample, () => new Sample())!;
Text.create(`Page1 add 1 to prop.p1: ${this.prop.f123.p123}`); |
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 } from './file1';
const person: MyInfo = {
age: 20,
address: {
i: "shanghai"
}
} |
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 {
prop1: string = '';
prop2: number = 0
}
let obj = new jsonTest();
const jsonStr = JSON.stringify(obj); // prop1 and prop2 will be obfuscated and should be retained. |
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
methodName2(@ParamDecorator param: string): void { // methodName2 should be retained.
}
} |
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.
class MyClass {}
let d = new MyClass(); // MyClass can be correctly obfuscated. |
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: taskId: , priority: , executeState:
taskpool:: Task Allocation: taskId: , priority: , executeState:
...
// Log 2: scaling log
taskpool:: maxThreads: , create num: , total num:
// Log 3: execution state log
taskpool:: Task Perform: name: , taskId: , priority: |
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 393913878464
// HiLog log snippet 2 (simulation)
// Check the second task. It takes 2s to complete.
18:28:28.223 taskpool:: taskId 394062838784 in seqRunner 393913878464 immediately.
18:28:28.224 taskpool:: Task Perform: name : , taskId : 394062838784, priority : 0
18:28:30.243 taskpool:: Task Perform End: taskId : 394062838784, performResult : Successful |
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 instanceof in main thread success");
} else {
console.log("test instanceof in main thread fail");
}
workerInstance.postMessageWithSharedSendable(a);
workerInstance.onerror = (err: ErrorEvent) => {
console.log("worker err :" + err.message)
}
}
testInstanceof() |
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 "test instanceof in worker thread success".
console.log("test instanceof in worker thread success");
} else {
console.log("test instanceof in worker thread fail");
}
} |
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 = collections.Array.create(calc.totalCount, collections.Array.create(2, ""));
return calc
}
add(a: number, b: number) {
let result = a + b;
this.newCalc(`${a} + ${b}`, `${result}`);
return result
}
sub(a: number, b: number) {
let result = a - b;
this.newCalc(`${a} - ${b}`, `${result}`);
return result
}
mul(a: number, b: number) {
let result = a * b;
this.newCalc(`${a} * ${b}`, `${result}`);
return result
}
div(a: number, b: number) {
let result = a / b;
this.newCalc(`${a} / ${b}`, `${result}`);
return result
}
getHistory(): collections.Array<collections.Array<string>> {
return this.history!;
}
showHistory() {
for (let i = 0; i < this.totalCount; i++) {
console.info(`${i}: ${this.history![i][0]} = ${this.history![i][1]}`)
}
}
private newCalc(opt: string, ret: string) {
let newRecord = new collections.Array<string>(opt, ret)
this.totalCount = this.history!.unshift(newRecord)
}
} |
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)
}, time)
})
}
} |
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 TimerSdk.init()
}
@Entry
@Component
struct Index {
calc?: Calculator
timer?: TimerSdk
aboutToAppear(): void {
taskpool.execute(initCalculator).then((ret) => {
this.calc = ret as Calculator
})
taskpool.execute(initTimerSdk).then((ret) => {
this.timer = ret as TimerSdk
})
}
build() {
Row() {
Column() {
Text("calculate add")
.id('add')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
let result = this.calc?.add(1, 2)
console.info(`Result is ${result}`)
})
Text("show history")
.id('show')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
this.calc?.showHistory()
})
Text("countdown")
.id('get')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
console.info(`Timer start`)
await this.timer?.Countdown(1000);
console.info(`Timer end`)
})
}
.width('100%')
}
.height('100%')
}
} |
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 data and schedule tasks concurrently.
let number: number = pixelBuffer.byteLength / 3;
let buffer1: ArrayBuffer = pixelBuffer.slice(0, number);
let buffer2: ArrayBuffer = pixelBuffer.slice(number, number * 2);
let buffer3: ArrayBuffer = pixelBuffer.slice(number * 2);
let group: taskpool.TaskGroup = new taskpool.TaskGroup();
group.addTask(imageProcessing, buffer1);
group.addTask(imageProcessing, buffer2);
group.addTask(imageProcessing, buffer3);
taskpool.execute(group, taskpool.Priority.HIGH).then((ret: Object) => {
// Step 3: Aggregate and process the result arrays.
})
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let buffer: ArrayBuffer = new ArrayBuffer(24);
histogramStatistic(buffer);
})
}
.width('100%')
}
.height('100%')
}
} |
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 = (() => {
// Receive error messages from the Worker thread.
})
// Send a training message to the Worker thread.
workerInstance.postMessage({ 'type': 0 }); |
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];
}
// onmessage logic of the Worker thread.
workerPort.onmessage = (e: MessageEvents): void => {
// Perform operations based on the type of data to transmit.
switch (e.data.type as number) {
case 0:
// Perform training.
optimize();
// Send a training success message to the host thread after training.
workerPort.postMessage({ type: 'message', value: 'train success.' });
break;
case 1:
// Perform prediction.
const output: number = predict(e.data.value as number);
// Send the prediction result to the host thread.
workerPort.postMessage({ type: 'predict', value: output });
break;
default:
workerPort.postMessage({ type: 'message', value: 'send message is invalid' });
break;
}
} |
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").onClick((event: ClickEvent) => {
ArkTools.hintGC(); // Call the method directly.
})
}
.width('100%')
}
.height('100%')
}
} |
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) {
return this.lock.lockAsync(() => {
this.isLogin = true;
this.loginUser = user
}, ArkTSUtils.locks.AsyncLockMode.EXCLUSIVE)
}
async logout(user?: string) {
return this.lock.lockAsync(() => {
this.isLogin = false
this.loginUser = ""
}, ArkTSUtils.locks.AsyncLockMode.EXCLUSIVE)
}
async getIsLogin(): Promise<boolean> {
return this.lock.lockAsync(() => {
return this.isLogin
}, ArkTSUtils.locks.AsyncLockMode.SHARED)
}
async getUser(): Promise<string> {
return this.lock.lockAsync(() => {
return this.loginUser!
}, ArkTSUtils.locks.AsyncLockMode.SHARED)
}
async setWifiState(state: boolean) {
return this.lock.lockAsync(() => {
this.wifiOn = state
}, ArkTSUtils.locks.AsyncLockMode.EXCLUSIVE)
}
async isWifiOn() {
return this.lock.lockAsync(() => {
return this.wifiOn;
}, ArkTSUtils.locks.AsyncLockMode.SHARED)
}
}
export let config = new Config() |
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;
}
console.info(`User[${await config.getUser()}] start download ...`)
return true;
}
@Entry
@Component
struct Index {
@State message: string = 'not login';
@State wifiState: string = "wifi off";
@State downloadResult: string = "";
input: string = ""
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
TextInput({ placeholder: "Enter user name" })
.fontSize(20)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onChange((value) => {
this.input = value;
})
Text("login")
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
if (!await config.getIsLogin() && this.input) {
this.message = "login: " + this.input
config.login(this.input)
}
})
.backgroundColor(0xcccccc)
Text("logout")
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
if (await config.getIsLogin()) {
this.message = "not login"
config.logout()
}
})
.backgroundColor(0xcccccc)
Text(this.wifiState)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
Toggle({ type: ToggleType.Switch })
.onChange(async (isOn: boolean) => {
await config.setWifiState(isOn)
this.wifiState = isOn ? "wifi on" : "wifi off";
})
Text("download")
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
let ret = await taskpool.execute(download)
this.downloadResult = ret ? "download success" : "download fail";
})
Text(this.downloadResult)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
}
.width('100%')
}
.height('100%')
}
} |
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[] = [];
// Add six IconItem data records.
for (let index = 0; index < count; index++) {
const numStart: number = index * 6;
// Use six images in the loop.
iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 1}`));
iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 2}`));
iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 3}`));
iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 4}`));
iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 5}`));
iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 6}`));
}
return iconItemSourceList;
} |
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() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let iconItemSourceList: IconItemSource[] = [];
// Create a task.
let loadPictureTask: taskpool.Task = new taskpool.Task(loadPicture, 30);
// Execute the task and return the result.
taskpool.execute(loadPictureTask).then((res: object) => {
// Execution result of the loadPicture method.
iconItemSourceList = res as IconItemSource[];
})
})
}
.width('100%')
}
.height('100%')
}
} |
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.READ_WRITE | fileIo.OpenMode.CREATE);
await fileIo.write(file.fd, data);
fileIo.close(file);
} |
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 filePath1: string = context.filesDir + "/path1.txt"; // Application file path
let filePath2: string = context.filesDir + "/path2.txt";
// Write data to the file cyclically.
let fileList: Array<string> = [];
fileList.push(filePath1);
fileList.push(filePath2)
for (let i: number = 0; i < fileList.length; i++) {
write('Hello World!', fileList[i]).then(() => {
console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`);
}).catch((err: BusinessError) => {
console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`)
return false;
})
}
return true;
} |
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 = this.getUIContext().getHostContext() as common.UIAbilityContext;
// Use TaskPool to execute the concurrent function with frequent I/O operations.
// In the case of a large array, the distribution of I/O intensive tasks can block the UI main thread. Therefore, multithreading is necessary.
taskpool.execute(concurrentTest, context).then(() => {
// Process the scheduling result.
console.info("taskpool: execute success")
})
})
}
.width('100%')
}
.height('100%')
}
} |
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(`result: ${arrayList2[0]}`); // Access the element at index 0. Output: result: 1
arrayList1[0] = 'one'; // Modify the element at index 0.
console.info(`result: ${arrayList1[0]}`); // Output: result: one
// Deque
import { Deque } from '@kit.ArkTS'; // Import the Deque module.
let deque1: Deque<string> = new Deque();
deque1.insertFront('a'); // Add an element with the value 'a' to the header.
let deque2: Deque<number> = new Deque();
deque2.insertFront(1); // Add an element with the value 1 to the header.
console.info(`result: ${deque2.getFirst()}`); // Access the first element. Output: result: 1
deque1.insertEnd('one'); // Add an element with the value 'one'.
console.info(`result: ${deque1.getLast()}`); // Access the last element. Output: result: one
// Stack
import { Stack } from '@kit.ArkTS'; // Import the Stack module.
let stack1: Stack<string> = new Stack();
stack1.push('a'); // Add an element with the value 'a' to the Stack.
let stack2: Stack<number> = new Stack();
stack2.push(1); // Add an element with the value 1 to the Stack.
console.info(`result: ${stack1.peek()}`); // Access the top element of the Stack. Output: result: a
console.info(`result: ${stack2.pop()}`); // Remove and return the top element. Output: result: 1
console.info(`result: ${stack2.length}`); // Output: result: 0
// List
import { List } from '@kit.ArkTS'; // Import the List module.
let list1: List<string> = new List();
list1.add('a'); // Add an element with the value 'a'.
let list2: List<number> = new List();
list2.insert(0, 0); // Insert an element with the value 0 at index 0.
let list3: List<Array<number>> = new List();
let b2 = [1, 2, 3];
list3.add(b2); // Add an element of the Array type.
console.info(`result: ${list1[0]}`); // Access the element at index 0. Output: result: a
console.info(`result: ${list3.get(0)}`); // Access the element at index 0. Output: result: 1,2,3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.