source stringlengths 14 113 | code stringlengths 10 21.3k |
|---|---|
application-dev\arkts-utils\worker-introduction.md | // Index.ets
import { ErrorEvent, MessageEvents, worker } from '@kit.ArkTS' |
application-dev\arkts-utils\worker-introduction.md | // Index.ets
@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(() => {
// Create a Worker object.
let workerInstance = new worker.ThreadWorker('entry/ets/workers/worker.ets');
// Register the onmessage callback. When the host thread receives a message from the Worker thread through the workerPort.postMessage interface, this callback is invoked and executed in the host thread.
workerInstance.onmessage = (e: MessageEvents) => {
let data: string = e.data;
console.info('workerInstance onmessage is: ', data);
}
// Register the onAllErrors callback to capture global exceptions generated during the onmessage callback, timer callback, and file execution of the Worker thread. This callback is executed in the host thread.
workerInstance.onAllErrors = (err: ErrorEvent) => {
console.error('workerInstance onAllErrors message is: ' + err.message);
}
// Register the onmessageerror callback. When the Worker object receives a message that cannot be serialized, this callback is invoked and executed in the host thread.
workerInstance.onmessageerror = () => {
console.error('workerInstance onmessageerror');
}
// Register the onexit callback. When the Worker object is destroyed, this callback is invoked and executed in the host thread.
workerInstance.onexit = (e: number) => {
// When the Worker object exits normally, the code is 0. When the Worker object exits abnormally, the code is 1.
console.info('workerInstance onexit code is: ', e);
}
// Send a message to the Worker thread.
workerInstance.postMessage('1');
})
}
.height('100%')
.width('100%')
}
} |
application-dev\arkts-utils\worker-introduction.md | // worker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
// Register the onmessage callback. When the Worker thread receives a message from the host thread through the postMessage interface, this callback is invoked and executed in the Worker thread.
workerPort.onmessage = (e: MessageEvents) => {
let data: string = e.data;
console.info('workerPort onmessage is: ', data);
// Send a message to the main thread.
workerPort.postMessage('2');
}
// Register the onmessageerror callback. When the Worker object receives a message that cannot be serialized, this callback is invoked and executed in the Worker thread.
workerPort.onmessageerror = () => {
console.error('workerPort onmessageerror');
}
// Register the onerror callback. When an exception occurs during the execution of the Worker thread, this callback is invoked and executed in the Worker thread.
workerPort.onerror = (err: ErrorEvent) => {
console.error('workerPort onerror err is: ', err.message);
} |
application-dev\arkts-utils\worker-introduction.md | // worker.ets
workerPort.onmessage = (e: MessageEvents) => {
console.info('worker thread receive message: ', e.data);
workerPort.postMessage('worker thread post message to main thread');
} |
application-dev\arkts-utils\worker-introduction.md | // Configure the dependency of the HAR in the entry module.
{
"name": "entry",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "",
"author": "",
"license": "",
"dependencies": {
"har": "file:../har"
}
} |
application-dev\arkts-utils\worker-introduction.md | // Index.ets
import { worker } from '@kit.ArkTS';
@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(() => {
// Use @ path loading mode and load the Worker thread file from the HAR.
let workerInstance = new worker.ThreadWorker('@har/ets/workers/worker.ets');
workerInstance.onmessage = () => {
console.info('main thread onmessage');
};
workerInstance.postMessage('hello world');
})
}
.height('100%')
.width('100%')
}
} |
application-dev\arkts-utils\worker-introduction.md | // Create a Worker thread (parent Worker) in the main thread, and create a Worker thread (child Worker) in the parent Worker.
// main thread
import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
// Create a parent Worker object in the main thread.
const parentworker = new worker.ThreadWorker('entry/ets/workers/parentworker.ets');
parentworker.onmessage = (e: MessageEvents) => {
console.info('The main thread receives a message from the parent Worker' + e.data);
}
parentworker.onexit = () => {
console.info('The parent Worker exits');
}
parentworker.onAllErrors = (err: ErrorEvent) => {
console.error('The main thread receives an error from the parent Worker ' + err);
}
parentworker.postMessage('The main thread sends a message to the parent Worker - recommended example'); |
application-dev\arkts-utils\worker-introduction.md | // parentworker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
// Create an object in the parent Worker for communicating with the main thread.
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e : MessageEvents) => {
if (e.data == 'The main thread sends a message to the parent Worker - recommended example') {
let childworker = new worker.ThreadWorker('entry/ets/workers/childworker.ets');
childworker.onmessage = (e: MessageEvents) => {
console.info('The parent Worker receives a message from the child Worker' + e.data);
if (e.data == 'The child Worker sends information to the parent Worker') {
workerPort.postMessage('The parent Worker sends a message to the main thread');
}
}
childworker.onexit = () => {
console.info('The child Worker exits');
// Destroy the parent Worker after the child Worker exits.
workerPort.close();
}
childworker.onAllErrors = (err: ErrorEvent) => {
console.error('An error occurred on the child Worker' + err);
}
childworker.postMessage('The parent Worker sends a message to the child Worker - recommended example');
}
} |
application-dev\arkts-utils\worker-introduction.md | // childworker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
// Create an object in the child Worker for communicating with the parent Worker.
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
if (e.data == 'The parent Worker sends a message to the child Worker - recommended example') {
// Service logic of the child Worker...
console.info('The service execution is complete, and the child Worker is destroyed');
workerPort.close();
}
} |
application-dev\arkts-utils\worker-introduction.md | // main thread
import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
const parentworker = new worker.ThreadWorker('entry/ets/workers/parentworker.ets');
parentworker.onmessage = (e: MessageEvents) => {
console.info('The main thread receives a message from the parent Worker' + e.data);
}
parentworker.onexit = () => {
console.info('The parent Worker exits');
}
parentworker.onAllErrors = (err: ErrorEvent) => {
console.error('The main thread receives an error from the parent Worker ' + err);
}
parentworker.postMessage('The main thread sends a message to the parent Worker'); |
application-dev\arkts-utils\worker-introduction.md | // parentworker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e : MessageEvents) => {
console.info('The parent Worker receives a message from the main thread' + e.data);
let childworker = new worker.ThreadWorker('entry/ets/workers/childworker.ets')
childworker.onmessage = (e: MessageEvents) => {
console.info('The parent Worker receives a message from the child Worker' + e.data);
}
childworker.onexit = () => {
console.info('The child Worker exits');
workerPort.postMessage('The parent Worker sends a message to the main thread');
}
childworker.onAllErrors = (err: ErrorEvent) => {
console.error('An error occurred on the child Worker' + err);
}
childworker.postMessage('The parent Worker sends a message to the child Worker');
// Destroy the parent Worker after the child Worker is created.
workerPort.close();
} |
application-dev\arkts-utils\worker-introduction.md | // childworker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
console.info('The child Worker receives a message' + e.data);
// After the parent Worker is destroyed, the child Worker sends a message to the parent Worker. The behavior is unpredictable.
workerPort.postMessage('The child Worker sends a message to the parent Worker');
setTimeout(() => {
workerPort.postMessage('The child Worker sends a message to the parent Worker');
}, 1000);
} |
application-dev\arkts-utils\worker-introduction.md | // main thread
import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
const parentworker = new worker.ThreadWorker('entry/ets/workers/parentworker.ets');
parentworker.onmessage = (e: MessageEvents) => {
console.info('The main thread receives a message from the parent Worker' + e.data);
}
parentworker.onexit = () => {
console.info('The parent Worker exits');
}
parentworker.onAllErrors = (err: ErrorEvent) => {
console.error('The main thread receives an error from the parent Worker ' + err);
}
parentworker.postMessage('The main thread sends a message to the parent Worker'); |
application-dev\arkts-utils\worker-introduction.md | // parentworker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e : MessageEvents) => {
console.info('The parent Worker receives a message from the main thread' + e.data);
// Create a child Worker after the parent Worker is destroyed. The behavior is unpredictable.
workerPort.close();
let childworker = new worker.ThreadWorker('entry/ets/workers/childworker.ets');
// Destroy the parent Worker before it is confirmed that the child Worker is successfully created. The behavior is unpredictable.
// let childworker = new worker.ThreadWorker('entry/ets/workers/childworker.ets');
// workerPort.close();
childworker.onmessage = (e: MessageEvents) => {
console.info('The parent Worker receives a message from the child Worker' + e.data);
}
childworker.onexit = () => {
console.info('The child Worker exits');
workerPort.postMessage('The parent Worker sends a message to the main thread');
}
childworker.onAllErrors = (err: ErrorEvent) => {
console.error('An error occurred on the child Worker' + err);
}
childworker.postMessage('The parent Worker sends a message to the child Worker');
} |
application-dev\arkts-utils\worker-introduction.md | // childworker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
console.info('The child Worker receives a message' + e.data);
} |
application-dev\arkts-utils\worker-invoke-mainthread-interface.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\worker-invoke-mainthread-interface.md | // WorkerCallGlobalUsage.ets
import worker from '@ohos.worker';
import { IconItemSource } from './IconItemSource';
// Create a Worker object.
const workerInstance: worker.ThreadWorker = new worker.ThreadWorker("entry/ets/pages/workers/Worker.ts");
class PicData {
public iconItemSourceList: IconItemSource[] = [];
public setUp(): string {
for (let index = 0; index < 20; index++) {
const numStart: number = index * 6;
// Use six images in the loop.
this.iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 1}`));
this.iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 2}`));
this.iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 3}`));
this.iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 4}`));
this.iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 5}`));
this.iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 6}`));
}
return "setUpIconItemSourceList success!";
}
}
let picData = new PicData();
// Register the object to be called on the Worker object.
workerInstance.registerGlobalCallObject("picData", picData);
workerInstance.postMessage("run setUp in picData"); |
application-dev\arkts-utils\worker-invoke-mainthread-interface.md | // Worker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
try {
// Call the method without parameters.
let res: string = workerPort.callGlobalCallObjectMethod("picData", "setUp", 0) as string;
console.error("worker: ", res);
} catch (error) {
// Handle exceptions.
console.error("worker: error code is " + error.code + " error message is " + error.message);
} |
application-dev\arkts-utils\worker-postMessage-sendable.md | // CopyEntry.ets
@Sendable
export class CopyEntry {
// Clone type.
type: string;
// File path.
filePath: string;
constructor(type: string, filePath: string) {
this.type = type;
this.filePath = filePath;
}
} |
application-dev\arkts-utils\worker-postMessage-sendable.md | // ParentWorker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker, collections, ArkTSUtils } from '@kit.ArkTS'
import { CopyEntry } from './CopyEntry'
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
// Calculate the number of tasks of worker1.
let count1 = 0;
// Calculate the number of tasks of worker2.
let count2 = 0;
// Calculate the total number of tasks.
let sum = 0;
// Asynchronous lock.
const asyncLock = new ArkTSUtils.locks.AsyncLock();
// Create a child Worker.
const copyWorker1 = new worker.ThreadWorker('entry/ets/pages/ChildWorker');
const copyWorker2 = new worker.ThreadWorker('entry/ets/pages/ChildWorker');
workerPort.onmessage = (e : MessageEvents) => {
let array = e.data as collections.Array<CopyEntry>;
sum = array.length;
for (let i = 0; i < array.length; i++) {
let entry = array[i];
if (entry.type === 'copy1') {
count1++;
// If the data type is copy1, transfer the data to copyWorker1.
copyWorker1.postMessageWithSharedSendable(entry);
} else if (entry.type === 'copy2') {
count2++;
// If the data type is copy2, transfer the data to copyWorker2.
copyWorker2.postMessageWithSharedSendable(entry);
}
}
}
copyWorker1.onmessage = async (e : MessageEvents) => {
console.info('copyWorker1 onmessage:' + e.data);
await asyncLock.lockAsync(() => {
count1--;
if (count1 == 0) {
// If all tasks of copyWorker1 are complete, close copyWorker1.
console.info('copyWorker1 close');
copyWorker1.terminate();
}
sum--;
if (sum == 0) {
// If all tasks are complete, close the parent Worker.
workerPort.close();
}
})
}
copyWorker2.onmessage = async (e : MessageEvents) => {
console.info('copyWorker2 onmessage:' + e.data);
await asyncLock.lockAsync(() => {
count2--;
sum--;
if (count2 == 0) {
// If all tasks of copyWorker2 are complete, close copyWorker2.
console.info('copyWorker2 close')
copyWorker2.terminate();
}
if (sum == 0) {
// If all tasks are complete, close the parent Worker.
workerPort.close();
}
})
}
workerPort.onmessageerror = (e : MessageEvents) => {
console.info('onmessageerror:' + e.data);
}
workerPort.onerror = (e : ErrorEvent) => {
console.info('onerror:' + e.message);
} |
application-dev\arkts-utils\worker-postMessage-sendable.md | // ChildWorker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker} from '@kit.ArkTS'
import { CopyEntry } from './CopyEntry'
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e : MessageEvents) => {
let data = e.data as CopyEntry;
// The copy operation is omitted.
console.info(data.filePath);
workerPort.postMessageWithSharedSendable("done");
}
workerPort.onmessageerror = (e : MessageEvents) => {
console.info('onmessageerror:' + e.data);
}
workerPort.onerror = (e : ErrorEvent) => {
console.info('onerror:' + e.message);
} |
application-dev\arkts-utils\worker-postMessage-sendable.md | // Index.ets
import { worker, collections } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
import { CopyEntry } from './CopyEntry'
function promiseCase() {
let p: Promise<void> = new Promise<void>((resolve: Function, reject: Function) => {
setTimeout(() => {
resolve(1);
}, 100)
}).then(undefined, (error: BusinessError) => {
})
return p;
}
async function postMessageTest() {
let ss = new worker.ThreadWorker("entry/ets/pages/ParentWorker");
let isTerminate = false;
ss.onexit = () => {
isTerminate = true;
}
let array = new collections.Array<CopyEntry>();
// Prepare data.
for (let i = 0; i < 4; i++) {
if (i % 2 == 0) {
array.push(new CopyEntry("copy1", "file://copy1.txt"));
} else {
array.push(new CopyEntry("copy2", "file://copy2.txt"));
}
}
// Send a message to the Worker thread.
ss.postMessageWithSharedSendable(array);
while (!isTerminate) {
await promiseCase();
}
console.info("Worker thread has exited");
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
postMessageTest();
})
}
.width('100%')
}
.height('100%')
}
} |
application-dev\arkts-utils\xml-conversion.md | import { convertxml } from '@kit.ArkTS'; |
application-dev\arkts-utils\xml-conversion.md | let xml: string =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
' <title>Happy</title>' +
' <todo>Work</todo>' +
' <todo>Play</todo>' +
'</note>';
let options: convertxml.ConvertOptions = {
// trim: false, indicating that spaces before and after the text are not deleted after conversion.
// declarationKey: "_declaration", indicating that _declaration is used to identify the file declaration after conversion.
// instructionKey: "_instruction", indicating that _instruction is used to identify instructions after conversion.
// attributesKey: "_attributes", indicating that _attributes is used to identify attributes after conversion.
// textKey: "_text", indicating that _text is used to identify tag values after conversion.
// cdataKey: "_cdata", indicating that _cdata is used to identify unparsed data after conversion.
// docTypeKey: "_doctype", indicating that _doctype is used to identify documents after conversion.
// commentKey: "_comment", indicating that _comment is used to identify comments after conversion.
// parentKey: "_parent", indicating that _parent is used to identify parent classes after conversion.
// typeKey: "_type", indicating that _type is used to identify types after conversion.
// nameKey: "_name", indicating that _name is used to identify tag names after conversion.
// elementsKey: "_elements", indicating that _elements is used to identify elements after conversion.
trim: false,
declarationKey: "_declaration",
instructionKey: "_instruction",
attributesKey: "_attributes",
textKey: "_text",
cdataKey: "_cdata",
doctypeKey: "_doctype",
commentKey: "_comment",
parentKey: "_parent",
typeKey: "_type",
nameKey: "_name",
elementsKey: "_elements"
} |
application-dev\arkts-utils\xml-conversion.md | let conv: convertxml.ConvertXML = new convertxml.ConvertXML();
let result: object = conv.fastConvertToJSObject(xml, options);
let strRes: string = JSON.stringify(result); // Convert the JavaScript object into a JSON string for explicit output.
console.info(strRes); |
application-dev\arkts-utils\xml-generation.md | import { xml, util } from '@kit.ArkTS'; |
application-dev\arkts-utils\xml-generation.md | // Method 1: Create an XmlSerializer object based on ArrayBuffer.
let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // Create a 2048-byte ArrayBuffer.
let serializer: xml.XmlSerializer = new xml.XmlSerializer(arrayBuffer); // Create an XmlSerializer object based on the ArrayBuffer.
// Method 2: Create an XmlSerializer object based on DataView.
// let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048);
// let dataView: DataView = new DataView(arrayBuffer);
// let serializer: xml.XmlSerializer = new xml.XmlSerializer(dataView); |
application-dev\arkts-utils\xml-generation.md | serializer.setDeclaration(); // Write the XML declaration.
serializer.startElement('bookstore'); // Write the start tag of an element.
serializer.startElement('book'); // Write the start tag of a nested element.
serializer.setAttributes('category', 'COOKING'); // Write attributes and attribute values.
serializer.startElement('title');
serializer.setAttributes('lang', 'en');
serializer.setText('Everyday'); // Write the tag value.
serializer.endElement(); // Write the end flag.
serializer.startElement('author');
serializer.setText('Giana');
serializer.endElement();
serializer.startElement('year');
serializer.setText('2005');
serializer.endElement();
serializer.endElement();
serializer.endElement(); |
application-dev\arkts-utils\xml-generation.md | let uint8Array: Uint8Array = new Uint8Array(arrayBuffer); // Use Uint8Array to read data from the ArrayBuffer.
let textDecoder: util.TextDecoder = util.TextDecoder.create(); // Call the TextDecoder class of the util module.
let result: string = textDecoder.decodeToString(uint8Array); // Decode the Uint8Array.
console.info(result); |
application-dev\arkts-utils\xml-parsing.md | import { xml, util } from '@kit.ArkTS'; // Use the API provided by the util module to encode text. |
application-dev\arkts-utils\xml-parsing.md | let strXml: string =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
'<title>Play</title>' +
'<lens>Work</lens>' +
'</note>';
let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // Encode the data to prevent garbled characters.
// Method 1: Create an XmlPullParser object based on ArrayBuffer.
let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8');
// Method 2: Create an XmlPullParser object based on DataView.
// let dataView: DataView = new DataView(arrBuffer.buffer as object as ArrayBuffer);
// let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8'); |
application-dev\arkts-utils\xml-parsing.md | function func(name: string, value: string): boolean {
if (name == 'note') {
console.info(name);
}
if (value == 'Play' || value == 'Work') {
console.info(' ' + value);
}
if (name == 'title' || name == 'lens') {
console.info(' ' + name);
}
return true; // The value true means to continue parsing, and false means to stop parsing.
} |
application-dev\arkts-utils\xml-parsing.md | let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func};
that.parseXml(options); |
application-dev\arkts-utils\xml-parsing.md | import { xml, util } from '@kit.ArkTS'; // Use the API provided by the util module to encode text. |
application-dev\arkts-utils\xml-parsing.md | let strXml: string =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
' <title>Play</title>' +
' <title>Happy</title>' +
' <lens>Work</lens>' +
'</note>';
let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // Encode the data to prevent garbled characters.
let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8'); |
application-dev\arkts-utils\xml-parsing.md | let str: string = '';
function func(name: string, value: string): boolean {
str += name + ' ' + value + ' ';
return true; // The value true means to continue parsing, and false means to stop parsing.
} |
application-dev\arkts-utils\xml-parsing.md | let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func};
that.parseXml(options);
console.info(str); // Print all attributes and their values at a time. |
application-dev\arkts-utils\xml-parsing.md | import { xml, util } from '@kit.ArkTS'; // Use the API provided by the util module to encode text. |
application-dev\arkts-utils\xml-parsing.md | let strXml: string =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
'<title>Play</title>' +
'</note>';
let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // Encode the data to prevent garbled characters.
let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8'); |
application-dev\arkts-utils\xml-parsing.md | let str: string = '';
function func(name: xml.EventType, value: xml.ParseInfo): boolean {
str = name +' ' + value.getDepth(); // getDepth is called to obtain the element depth.
console.info(str);
return true; // The value true means to continue parsing, and false means to stop parsing.
} |
application-dev\arkts-utils\xml-parsing.md | let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func};
that.parseXml(options); |
application-dev\arkts-utils\xml-parsing.md | import { xml, util } from '@kit.ArkTS';
let strXml: string =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<book category="COOKING">' +
'<title lang="en">Everyday</title>' +
'<author>Giana</author>' +
'</book>';
let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml);
let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8');
let str: string = '';
function tagFunc(name: string, value: string): boolean {
str = name + value;
console.info('tag-' + str);
return true;
}
function attFunc(name: string, value: string): boolean {
str = name + ' ' + value;
console.info('attri-' + str);
return true;
}
function tokenFunc(name: xml.EventType, value: xml.ParseInfo): boolean {
str = name + ' ' + value.getDepth();
console.info('token-' + str);
return true;
}
let options: xml.ParseOptions = {
supportDoctype: true,
ignoreNameSpace: true,
tagValueCallbackFunction: tagFunc,
attributeValueCallbackFunction: attFunc,
tokenValueCallbackFunction: tokenFunc
};
that.parseXml(options); |
application-dev\basic-services\account\auth-domain-account.md | import { osAccount } from '@kit.BasicServicesKit'; |
application-dev\basic-services\account\auth-domain-account.md | let domainAccountInfo: osAccount.DomainAccountInfo = {
domain: 'CHINA',
accountName: 'zhangsan'
}
let credential: Uint8Array = new Uint8Array([0]); |
application-dev\basic-services\account\auth-domain-account.md | let callback: osAccount.IUserAuthCallback = {
onResult: (resultCode: number, authResult: osAccount.AuthResult) => {
console.log('auth resultCode = ' + resultCode);
console.log('auth authResult = ' + JSON.stringify(authResult));
}
} |
application-dev\basic-services\account\auth-domain-account.md | try {
osAccount.DomainAccountManager.auth(domainAccountInfo, credential, callback);
} catch (err) {
console.error('auth exception = ' + JSON.stringify(err));
} |
application-dev\basic-services\account\auth-domain-account.md | let callback: osAccount.IUserAuthCallback = {
onResult: (resultCode: number, authResult: osAccount.AuthResult) => {
console.log('authWithPopup resultCode = ' + resultCode);
console.log('authWithPopup authResult = ' + JSON.stringify(authResult));
}
} |
application-dev\basic-services\account\auth-domain-account.md | try {
osAccount.DomainAccountManager.authWithPopup(callback)
} catch (err) {
console.error('authWithPopup exception = ' + JSON.stringify(err));
} |
application-dev\basic-services\account\control-os-account-by-constraints.md | import { osAccount } from '@kit.BasicServicesKit'; |
application-dev\basic-services\account\control-os-account-by-constraints.md | let accountManager = osAccount.getAccountManager(); |
application-dev\basic-services\account\control-os-account-by-constraints.md | let localId: number = 100;
let constraint: string[] = [ 'constraint.wifi.set' ]; |
application-dev\basic-services\account\control-os-account-by-constraints.md | try {
accountManager.setOsAccountConstraints(localId, constraint, true);
console.log('setOsAccountConstraints successfully');
} catch (err) {
console.error('setOsAccountConstraints failed, error: ' + JSON.stringify(err));
} |
application-dev\basic-services\account\control-os-account-by-constraints.md | let localId: number = 100;
let constraint: string = 'constraint.wifi.set'; |
application-dev\basic-services\account\control-os-account-by-constraints.md | accountManager.isOsAccountConstraintEnabled(localId, constraint).then((isEnabled: boolean) => {
if (isEnabled) {
// Your business logic
}
}); |
application-dev\basic-services\account\manage-application-account.md | import { appAccount, BusinessError } from '@kit.BasicServicesKit'; |
application-dev\basic-services\account\manage-application-account.md | const appAccountManager = appAccount.createAppAccountManager(); |
application-dev\basic-services\account\manage-application-account.md | let name: string = "ZhangSan";
let options: appAccount.CreateAccountOptions = {
customData: {
age: '10'
}
}; |
application-dev\basic-services\account\manage-application-account.md | appAccountManager.createAccount(name, options).then(()=>{
console.log('createAccount successfully');
}).catch((err: BusinessError)=>{
console.error('createAccount failed, error: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-application-account.md | appAccountManager.getAllAccounts().then((data: appAccount.AppAccountInfo[]) => {
console.log('getAllAccounts successfully, data: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error('getAllAccounts failed, error: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-application-account.md | let name: string = 'ZhangSan';
let credentialType: string = 'PIN_SIX';
let credential: string = 'xxxxxx'; |
application-dev\basic-services\account\manage-application-account.md | appAccountManager.getCredential(name, credentialType).then((data: string) => {
console.log('getCredential successfully, data: ' + data);
}).catch((err: BusinessError) => {
console.error('getCredential failed, error: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-application-account.md | appAccountManager.setCredential(name, credentialType, credential).then(() => {
console.log('setCredential successfully');
}).catch((err: BusinessError) => {
console.error('setCredential failed: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-application-account.md | let name: string = 'ZhangSan';
let key: string = 'age';
let value: string = '12'; |
application-dev\basic-services\account\manage-application-account.md | appAccountManager.setCustomData(name, key, value).then(() => {
console.log('setCustomData successfully');
}).catch((err: BusinessError) => {
console.error('setCustomData failed: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-application-account.md | appAccountManager.getCustomData(name, key).then((data: string) => {
console.log('getCustomData successfully, data: ' + data);
}).catch((err: BusinessError) => {
console.error('getCustomData failed, error: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-application-account.md | let name: string = 'ZhangSan';
let owner: string = 'com.example.accountjsdemo';
let authType: string = 'getSocialData';
let token: string = 'xxxxxx'; |
application-dev\basic-services\account\manage-application-account.md | appAccountManager.setAuthToken(name, authType, token).then(() => {
console.log('setAuthToken successfully');
}).catch((err: BusinessError) => {
console.error('setAuthToken failed: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-application-account.md | appAccountManager.getAuthToken(name, owner, authType).then((data: string) => {
console.log('getAuthToken successfully, data: ' + data);
}).catch((err: BusinessError) => {
console.error('getAuthToken failed, error: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-application-account.md | let name: string = 'Zhangsan';
appAccountManager.removeAccount(name).then(() => {
console.log('removeAccount successfully');
}).catch((err: BusinessError) => {
console.error('removeAccount failed, error: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-distributed-account.md | import { distributedAccount, BusinessError } from '@kit.BasicServicesKit'; |
application-dev\basic-services\account\manage-distributed-account.md | const distributedAccountAbility = distributedAccount.getDistributedAccountAbility(); |
application-dev\basic-services\account\manage-distributed-account.md | let distributedInfo: distributedAccount.DistributedInfo = {
name: 'ZhangSan',
id: '12345',
event: 'Ohos.account.event.LOGIN',
}; |
application-dev\basic-services\account\manage-distributed-account.md | distributedAccountAbility.setOsAccountDistributedInfo(distributedInfo).then(() => {
console.log('setOsAccountDistributedInfo successfully');
}).catch((err: BusinessError) => {
console.error('setOsAccountDistributedInfo exception: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-distributed-account.md | distributedAccountAbility.getOsAccountDistributedInfo().then((data: distributedAccount.DistributedInfo) => {
console.log('distributed information: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error('getOsAccountDistributedInfo exception: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-distributed-account.md | let distributedInfo: distributedAccount.DistributedInfo = {
name: 'ZhangSan',
id: '12345',
event: 'Ohos.account.event.LOGOUT',
}; |
application-dev\basic-services\account\manage-distributed-account.md | distributedAccountAbility.setOsAccountDistributedInfo(distributedInfo).then(() => {
console.log('setOsAccountDistributedInfo successfully');
}).catch((err: BusinessError) => {
console.error('setOsAccountDistributedInfo exception: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-distributed-account.md | let localId: number = 100;
let distributedInfo: distributedAccount.DistributedInfo = {
name: 'ZhangSan',
id: '12345',
event: 'Ohos.account.event.LOGIN',
}; |
application-dev\basic-services\account\manage-distributed-account.md | distributedAccountAbility.setOsAccountDistributedInfoByLocalId(localId, distributedInfo).then(() => {
console.log('setOsAccountDistributedInfoByLocalId successfully');
}).catch((err: BusinessError) => {
console.error('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-distributed-account.md | distributedAccountAbility.getOsAccountDistributedInfoByLocalId(localId).then((data: distributedAccount.DistributedInfo) => {
console.log('distributed information: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-distributed-account.md | let localId: number = 100;
let distributedInfo: distributedAccount.DistributedInfo = {
name: 'ZhangSan',
id: '12345',
event: 'Ohos.account.event.LOGOUT',
}; |
application-dev\basic-services\account\manage-distributed-account.md | distributedAccountAbility.setOsAccountDistributedInfoByLocalId(localId, distributedInfo).then(() => {
console.log('setOsAccountDistributedInfoByLocalId successfully');
}).catch((err: BusinessError) => {
console.error('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-domain-account.md | import { osAccount, BusinessError } from '@kit.BasicServicesKit'; |
application-dev\basic-services\account\manage-domain-account.md | let osAccountMgr = osAccount.getAccountManager(); |
application-dev\basic-services\account\manage-domain-account.md | let domainAccountInfo: osAccount.DomainAccountInfo = {
accountName: 'testAccountName',
domain: 'testDomain'
} |
application-dev\basic-services\account\manage-domain-account.md | osAccount.DomainAccountManager.hasAccount(domainAccountInfo).then((isAccountExisted: boolean)=>{
console.log('execute hasAccount successfully, isAccountExisted:' + JSON.stringify(isAccountExisted));
}).catch((err: BusinessError)=>{
console.error('execute hasAccount err:' + JSON.stringify(err));
}); |
application-dev\basic-services\account\manage-domain-account.md | let domainInfo: osAccount.DomainAccountInfo = {
domain: 'testDomain',
accountName: 'testAccountName'
}; |
application-dev\basic-services\account\manage-domain-account.md | try {
osAccountMgr.createOsAccountForDomain(osAccount.OsAccountType.NORMAL, domainInfo,
(err: BusinessError, osAccountInfo: osAccount.OsAccountInfo)=>{
if (err) {
console.error('createOsAccountForDomain exception:' + JSON.stringify(err));
} else {
console.log('createOsAccountForDomain osAccountInfo:' + JSON.stringify(osAccountInfo));
}
});
} catch (e) {
console.error('createOsAccountForDomain exception: ' + JSON.stringify(e));
} |
application-dev\basic-services\account\manage-domain-account.md | let domainInfo: osAccount.DomainAccountInfo = {
domain: 'testDomain',
accountName: 'testAccountName'
};
let localId: number = 0;
try {
localId = await osAccountMgr.getOsAccountLocalIdForDomain(domainInfo);
} catch (err) {
console.error('getOsAccountLocalIdForDomain exception: ' + JSON.stringify(err));
} |
application-dev\basic-services\account\manage-domain-account.md | try {
osAccountMgr.removeOsAccount(localId, (err: BusinessError)=>{
if (err) {
console.error('removeOsAccount failed, error: ' + JSON.stringify(err));
} else {
console.log('removeOsAccount successfully');
}
});
} catch (err) {
console.error('removeOsAccount exception: ' + JSON.stringify(err));
} |
application-dev\basic-services\account\manage-domain-account.md | let options: osAccount.GetDomainAccountInfoOptions = {
domain: 'testDomain',
accountName: 'testAccountName'
} |
application-dev\basic-services\account\manage-domain-account.md | try {
osAccount.DomainAccountManager.getAccountInfo(options,
(err: BusinessError, result: osAccount.DomainAccountInfo) => {
if (err) {
console.error('call getAccountInfo failed, error: ' + JSON.stringify(err));
} else {
console.log('getAccountInfo result: ' + result);
}
});
} catch (err) {
console.error('getAccountInfo exception = ' + JSON.stringify(err));
} |
application-dev\basic-services\account\manage-domain-plugin.md | import { osAccount, AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; |
application-dev\basic-services\account\manage-domain-plugin.md | let accountMgr = osAccount.getAccountManager() |
application-dev\basic-services\account\manage-domain-plugin.md | let plugin: osAccount.DomainPlugin = {
auth: (domainAccountInfo: osAccount.DomainAccountInfo, credential: Uint8Array,
callback: osAccount.IUserAuthCallback) => {
console.info("plugin auth domain" + domainAccountInfo.domain)
console.info("plugin auth accountName" + domainAccountInfo.accountName)
console.info("plugin auth accountId" + domainAccountInfo.accountId)
let result: osAccount.AuthResult = {
token: new Uint8Array([0]),
remainTimes: 5,
freezingTime: 0
};
callback.onResult(0, result);
},
authWithPopup: (domainAccountInfo: osAccount.DomainAccountInfo,
callback: osAccount.IUserAuthCallback) => {
console.info("plugin authWithPopup domain" + domainAccountInfo.domain)
console.info("plugin authWithPopup accountName" + domainAccountInfo.accountName)
console.info("plugin authWithPopup accountId" + domainAccountInfo.accountId)
let result: osAccount.AuthResult = {
token: new Uint8Array([0]),
remainTimes: 5,
freezingTime: 0
};
callback.onResult(0, result);
},
authWithToken: (domainAccountInfo: osAccount.DomainAccountInfo, token: Uint8Array, callback: osAccount.IUserAuthCallback) => {
console.info("plugin authWithToken domain" + domainAccountInfo.domain)
console.info("plugin authWithToken accountName" + domainAccountInfo.accountName)
console.info("plugin authWithToken accountId" + domainAccountInfo.accountId)
let result: osAccount.AuthResult = {
token: new Uint8Array([0]),
remainTimes: 5,
freezingTime: 0
};
callback.onResult(0, result);
},
getAccountInfo: (options: osAccount.GetDomainAccountInfoPluginOptions,
callback: AsyncCallback<osAccount.DomainAccountInfo>) => {
console.info("plugin getAccountInfo domain")
let domainAccountId = Date.now().toString()
let code: BusinessError = {
code: 0,
name: "mock_name",
message: "mock_message"
};
let domainStr: string = '';
if (options.domain != undefined) {
domainStr = options.domain
}
let accountInfo: osAccount.DomainAccountInfo = {
domain: domainStr,
accountName: options.accountName,
accountId: domainAccountId,
isAuthenticated: false
};
callback(code, accountInfo);
},
getAuthStatusInfo: (domainAccountInfo: osAccount.DomainAccountInfo,
callback: AsyncCallback<osAccount.AuthStatusInfo>) => {
console.info("plugin getAuthStatusInfo domain" + domainAccountInfo.domain)
console.info("plugin getAuthStatusInfo accountName" + domainAccountInfo.accountName)
console.info("plugin getAuthStatusInfo accountId" + domainAccountInfo.accountId)
let code: BusinessError = {
code: 0,
name: "mock_name",
message: "mock_message"
};
let statusInfo: osAccount.AuthStatusInfo = {
remainTimes: 5,
freezingTime: 0
};
callback(code, statusInfo);
},
bindAccount: (domainAccountInfo: osAccount.DomainAccountInfo, localId: number,
callback: AsyncCallback<void>) => {
console.info("plugin bindAccount domain" + domainAccountInfo.domain)
console.info("plugin bindAccount accountName" + domainAccountInfo.accountName)
console.info("plugin bindAccount accountId" + domainAccountInfo.accountId)
let code: BusinessError = {
code: 0,
name: "mock_name",
message: "mock_message"
};
callback(code);
},
unbindAccount: (domainAccountInfo: osAccount.DomainAccountInfo, callback: AsyncCallback<void>) => {
console.info("plugin unbindAccount domain" + domainAccountInfo.domain)
console.info("plugin unbindAccount accountName" + domainAccountInfo.accountName)
console.info("plugin unbindAccount accountId" + domainAccountInfo.accountId)
},
isAccountTokenValid: (domainAccountInfo: osAccount.DomainAccountInfo, token: Uint8Array,
callback: AsyncCallback<boolean>) => {
console.info("plugin isAccountTokenValid domain" + domainAccountInfo.domain)
console.info("plugin isAccountTokenValid accountName" + domainAccountInfo.accountName)
console.info("plugin isAccountTokenValid accountId" + domainAccountInfo.accountId)
let code: BusinessError = {
code: 0,
name: "mock_name",
message: "mock_message"
};
callback(code, true);
},
getAccessToken: (options: osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback<Uint8Array>) => {
console.info("plugin getAccessToken domain")
let code: BusinessError = {
code: 0,
name: "mock_name",
message: "mock_message"
};
let token: Uint8Array = new Uint8Array([0]);
callback(code, token);
}
} |
application-dev\basic-services\account\manage-domain-plugin.md | try {
osAccount.DomainAccountManager.registerPlugin(plugin)
console.info("registerPlugin success")
} catch (err) {
console.error("registerPlugin err: " + JSON.stringify(err));
} |
application-dev\basic-services\account\manage-domain-plugin.md | try {
osAccount.DomainAccountManager.unregisterPlugin();
console.log('unregisterPlugin success.');
} catch(err) {
console.error('unregisterPlugin err:' + JSON.stringify(err));
} |
application-dev\basic-services\account\manage-os-account-credential.md | import { osAccount } from '@kit.BasicServicesKit'; |
application-dev\basic-services\account\manage-os-account-credential.md | let userIDM: osAccount.UserIdentityManager = new osAccount.UserIdentityManager(); |
application-dev\basic-services\account\manage-os-account-credential.md | let pinData: Uint8Array = new Uint8Array([31, 32, 33, 34, 35, 36]); // you can obtain a PIN through other ways.
let inputer: osAccount.IInputer = {
onGetData: (authSubType: osAccount.AuthSubType, callback: osAccount.IInputData) => {
callback.onSetData(authSubType, pinData);
}
} |
application-dev\basic-services\account\manage-os-account-credential.md | let pinAuth: osAccount.PINAuth = new osAccount.PINAuth();
pinAuth.registerInputer(inputer); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.