Dataset Viewer
Auto-converted to Parquet Duplicate
source
stringlengths
14
113
code
stringlengths
10
21.3k
application-dev\accessibility\accessibilityextensionability.md
import { AccessibilityExtensionAbility, AccessibilityEvent } from '@kit.AccessibilityKit'; import AccessibilityManager from './AccessibilityManager'; class AccessibilityExtAbility extends AccessibilityExtensionAbility { onConnect() { console.info(`AccessibilityExtAbility onConnect`); // Initialize the service logic. AccessibilityManager.getInstance().onStart(this.context); } onDisconnect() { console.info(`AccessibilityExtAbility onDisconnect`); // Reclaim resources and exit the service logic. AccessibilityManager.getInstance().onStop(); } onAccessibilityEvent(accessibilityEvent: AccessibilityEvent) { console.info(`AccessibilityExtAbility onAccessibilityEvent: ${JSON.stringify(accessibilityEvent)}`); // Process the service logic based on the event information. AccessibilityManager.getInstance().onEvent(accessibilityEvent); } } export default AccessibilityExtAbility;
application-dev\accessibility\accessibilityextensionability.md
import { AccessibilityElement, AccessibilityEvent, AccessibilityExtensionContext, ElementAttributeKeys } from '@kit.AccessibilityKit'; interface Rect { left: number, top: number, width: number, height: number, } // Attribute information to be queried let wantedAttribute: ElementAttributeKeys[] = ['bundleName', 'text', 'description', 'windowId']; type attributeValues = string | number | boolean | AccessibilityElement | AccessibilityElement[] | string[] | Rect; export default class AccessibilityManager { private static instance: AccessibilityManager; accessibleContext?: AccessibilityExtensionContext; currentPageElementArray: Array<AccessibilityElement> | null = null; static getInstance(): AccessibilityManager { if (!AccessibilityManager.instance) { AccessibilityManager.instance = new AccessibilityManager(); } return AccessibilityManager.instance; } onStart(context: AccessibilityExtensionContext) { console.info(`AccessibilityManager onStart`); this.accessibleContext = context; } onStop() { console.info(`AccessibilityManager onStop`); this.accessibleContext = undefined; } onEvent(accessibilityEvent: AccessibilityEvent): void { console.info(`AccessibilityManager onEvent`); switch (accessibilityEvent.eventType) { case 'rightThenDown': // Obtain all nodes on the current screen. this.getCurrentPageAllElement(); break; case 'leftThenDown': // Obtain all nodes. this.printAllElementInfo(); break; default: break; } } async getCurrentPageAllElement(): Promise<void> { console.info(`AccessibilityManager getCurrentPageAllElement`); let rootElement: AccessibilityElement; if(!this.accessibleContext){ console.error(`AccessibilityManager accessibleContext undefined`); return; } try { rootElement = await this.accessibleContext?.getWindowRootElement(); this.currentPageElementArray = await this.getAttributeValue(rootElement, 'children') as AccessibilityElement[]; } catch (error) { console.error(`AccessibilityExtAbility Failed to getWindowRootElement. Cause:${JSON.stringify(error)}`); } } async getElementWantedInfo(accessibilityElement: AccessibilityElement, wantedAttribute: ElementAttributeKeys[]): Promise<string | null> { console.info(`AccessibilityUtils getElementAllInfo`); if (accessibilityElement === null) { console.error(`AccessibilityUtils accessibilityElement is null`); return null; } let info = ''; let value: attributeValues | null; for (let name of wantedAttribute) { value = await this.getAttributeValue(accessibilityElement, name); info = info.concat(name + ': ' + value + ' '); } return info; } async getAttributeValue(accessibilityElement: AccessibilityElement, key: ElementAttributeKeys): Promise<attributeValues | null> { console.info(`AccessibilityUtils getAttributeValue`); let value: attributeValues; let keys = await accessibilityElement.attributeNames(); let isExit = false; for (let keyString of keys) { if (key == keyString) { isExit = true; } } if (isExit) { try { value = await accessibilityElement.attributeValue(key); return value; } catch (error) { console.error(`AccessibilityUtils Failed to get attributeValue of ${key} . Cause: ${JSON.stringify(error)}`); } } return null; } async printAllElementInfo(): Promise<void> { console.info(`AccessibilityManager printAllElementInfo`); if (this.currentPageElementArray === null || this.currentPageElementArray.length === 0) { console.error(`AccessibilityManager currentPageElementArray is null`); return; } let info: string | null = null; for (let index = 0; index < this.currentPageElementArray.length; index++) { info = await this.getElementWantedInfo(this.currentPageElementArray[index], wantedAttribute); console.info(`AccessibilityManager element information: ${info}`); } } }
application-dev\accessibility\accessibilityextensionability.md
onAccessibilityEvent(accessibilityEvent: AccessibilityEvent) { console.info('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); if (accessibilityEvent.eventType === 'rightThenDown') { console.info('AccessibilityExtAbility onAccessibilityEvent: rightThenDown'); // TODO: Develop custom logic. } }
application-dev\ads-service\oaid\oaid-service-sys.md
{ "module": { "requestPermissions": [ { "name": "ohos.permission.APP_TRACKING_CONSENT", "reason": "$string:reason", "usedScene": { "abilities": [ "EntryFormAbility" ], "when": "inuse" } } ] } }
application-dev\ads-service\oaid\oaid-service-sys.md
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; import { BusinessError } from '@ohos.base'; import hilog from '@ohos.hilog'; import common from '@ohos.app.ability.common'; function requestOAIDTrackingConsentPermissions(context: common.Context): void { // Display a dialog box when the page is displayed to request the user to grant the ad tracking permission. const atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); try { atManager.requestPermissionsFromUser(context, ["ohos.permission.APP_TRACKING_CONSENT"]).then((data) => { if (data.authResults[0] == 0) { hilog.info(0x0000, 'testTag', '%{public}s', 'request permission success'); } else { hilog.error(0x0000, 'testTag', '%{public}s', 'user rejected'); } }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', '%{public}s', `request permission failed, error: ${err.code} ${err.message}`); }) } catch (err) { hilog.error(0x0000, 'testTag', '%{public}s', `catch err->${err.code}, ${err.message}`); } }
application-dev\ads-service\oaid\oaid-service-sys.md
import identifier from '@ohos.identifier.oaid'; import hilog from '@ohos.hilog'; // Reset the OAID. try { identifier.resetOAID(); } catch (err) { hilog.error(0x0000, 'testTag', '%{public}s', `reset oaid catch error: ${err.code} ${err.message}`); }
application-dev\ads-service\oaid\oaid-service.md
{ "module": { "requestPermissions": [ { "name": "ohos.permission.APP_TRACKING_CONSENT", "reason": "$string:reason", "usedScene": { "abilities": [ "EntryFormAbility" ], "when": "inuse" } } ] } }
application-dev\ads-service\oaid\oaid-service.md
import { identifier } from '@kit.AdsKit'; import { abilityAccessCtrl, common } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; function requestOAIDTrackingConsentPermissions(context: common.Context): void { // When the page is displayed, request the user to grant the permission ohos.permission.APP_TRACKING_CONSENT. const atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); try { atManager.requestPermissionsFromUser(context, ["ohos.permission.APP_TRACKING_CONSENT"]).then((data) => { if (data.authResults[0] == 0) { hilog.info(0x0000, 'testTag', '%{public}s', 'succeeded in requesting permission'); identifier.getOAID((err: BusinessError, data: string) => { if (err.code) { hilog.error(0x0000, 'testTag', '%{public}s', `get oaid failed, error: ${err.code} ${err.message}`); } else { const oaid: string = data; hilog.info(0x0000, 'testTag', '%{public}s', `succeeded in getting oaid by callback , oaid: ${oaid}`); } }); } else { hilog.error(0x0000, 'testTag', '%{public}s', 'user rejected'); } }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', '%{public}s', `request permission failed, error: ${err.code} ${err.message}`); }) } catch (err) { hilog.error(0x0000, 'testTag', '%{public}s', `catch err->${err.code}, ${err.message}`); } }
application-dev\ai\mindspore\mindspore-asr-based-native.md
// player.ets import { media } from '@kit.MediaKit'; import { common } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { audio } from '@kit.AudioKit'; import { UIContext } from '@kit.ArkUI'; export default class AVPlayerDemo { private isSeek: boolean = false; // Disable the seek operation. // Set the AVPlayer callback. setAVPlayerCallback(avPlayer: media.AVPlayer) { // Callback for the seek operation. avPlayer.on('seekDone', (seekDoneTime: number) => { console.info(`MS_LITE_LOG: AVPlayer seek succeeded, seek time is ${seekDoneTime}`); }); // Callback invoked if an error occurs while the AVPlayer is playing audio. In such a case, reset() is called to reset the AVPlayer. avPlayer.on('error', (err: BusinessError) => { console.error(`MS_LITE_LOG: Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`); avPlayer.reset(); // Call reset() to reset the AVPlayer, which enters the idle state. }); // Callback for state changes. avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => { switch (state) { case 'idle': // This state is reported upon a successful callback of reset(). console.info('MS_LITE_LOG: AVPlayer state idle called.'); avPlayer.release(); // Call release() to release the instance. break; case 'initialized': // This state is reported when the AVPlayer sets the playback source. console.info('MS_LITE_LOG: AVPlayer state initialized called.'); avPlayer.audioRendererInfo = { usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. rendererFlags: 0 // Audio renderer flag. }; avPlayer.prepare(); break; case 'prepared': // This state is reported upon a successful callback of prepare(). console.info('MS_LITE_LOG: AVPlayer state prepared called.'); avPlayer.play(); // Call play() to start playback. break; case 'playing': // This state is reported upon a successful callback of play(). console.info('MS_LITE_LOG: AVPlayer state playing called.'); if (this.isSeek) { console.info('MS_LITE_LOG: AVPlayer start to seek.'); avPlayer.seek(0); // Seek to the end of the audio. } else { // When the seek operation is not supported, the playback continues until it reaches the end. console.info('MS_LITE_LOG: AVPlayer wait to play end.'); } break; case 'paused': // This state is reported upon a successful callback of pause(). console.info('MS_LITE_LOG: AVPlayer state paused called.'); setTimeout(() => { console.info('MS_LITE_LOG: AVPlayer paused wait to play again'); avPlayer.play(); // After the playback is paused for 3 seconds, call the play API again to start playback. }, 3000); break; case 'completed': // This state is reported upon the completion of the playback. console.info('MS_LITE_LOG: AVPlayer state completed called.'); avPlayer.stop(); // Call stop() to stop the playback. break; case 'stopped': // This state is reported upon a successful callback of stop(). console.info('MS_LITE_LOG: AVPlayer state stopped called.'); avPlayer.reset(); // Call reset() to reset the AVPlayer. break; case 'released': console.info('MS_LITE_LOG: AVPlayer state released called.'); break; default: console.info('MS_LITE_LOG: AVPlayer state unknown called.'); break; } }); } // Use the resource management API to obtain the audio file and play the audio file through the fdSrc attribute. async avPlayerFdSrcDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); // Create a callback for state changes. this.setAVPlayerCallback(avPlayer); // Call getRawFd of the resourceManager member of UIAbilityContext to obtain the media asset URL. // The return type is {fd,offset,length}, where fd indicates the file descriptor address of the HAP file, offset indicates the media asset offset, and length indicates the duration of the media asset to play. let context = new UIContext().getHostContext() as common.UIAbilityContext; let fileDescriptor = await context.resourceManager.getRawFd('zh.wav'); let avFileDescriptor: media.AVFileDescriptor = { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length }; this.isSeek = true; // Enable the seek operation. // Assign a value to fdSrc to trigger the reporting of the initialized state. avPlayer.fdSrc = avFileDescriptor; } }
application-dev\ai\mindspore\mindspore-asr-based-native.md
export const runDemo: (a: Object) => string;
application-dev\ai\mindspore\mindspore-asr-based-native.md
// Index.ets import msliteNapi from 'libentry.so' import AVPlayerDemo from './player'; import { transverter, TransverterType, TransverterLanguage } from "@nutpi/chinese_transverter" @Entry @Component struct Index { @State message: string = 'MSLite Whisper Demo'; @State wavName: string = 'zh.wav'; @State content: string = ''; build() { Row() { Column() { Text(this.message) .fontSize(30) .fontWeight(FontWeight.Bold); Button() { Text('Play Audio') .fontSize(20) .fontWeight(FontWeight.Medium) } .type(ButtonType.Capsule) .margin({ top: 20 }) .backgroundColor('#0D9FFB') .width('40%') .height('5%') .onClick(async () =>{ // Invoke functions in the avPlayerFdSrcDemo class. console.info('MS_LITE_LOG: begin to play wav.'); let myClass = new AVPlayerDemo(); myClass.avPlayerFdSrcDemo(); }) Button() { Text ('Recognize Audio') .fontSize(20) .fontWeight(FontWeight.Medium) } .type(ButtonType.Capsule) .margin({ top: 20 }) .backgroundColor('#0D9FFB') .width('40%') .height('5%') .onClick(() => { let resMgr = this.getUIContext()?.getHostContext()?.getApplicationContext().resourceManager; // Call the encapsulated runDemo function. console.info('MS_LITE_LOG: *** Start MSLite Demo ***'); let output = msliteNapi.runDemo(resMgr); console.info('MS_LITE_LOG: output length = ', output.length, ';value = ', output.slice(0, 20)); this.content = output; console.info('MS_LITE_LOG: *** Finished MSLite Demo ***'); }) // Display the recognized content. if (this.content) { Text ('Recognized content:\n' + transverter({ type: TransverterType.SIMPLIFIED, str: this.content, language: TransverterLanguage.ZH_CN }) + '\n').focusable(true).fontSize(20).height('20%') } }.width('100%') } .height('100%') } }
application-dev\ai\mindspore\mindspore-guidelines-based-js.md
// Index.ets import { photoAccessHelper } from '@kit.MediaLibraryKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { image } from '@kit.ImageKit'; import { fileIo } from '@kit.CoreFileKit'; @Entry @Component struct Index { @State modelName: string = 'mobilenetv2.ms'; @State modelInputHeight: number = 224; @State modelInputWidth: number = 224; @State uris: Array<string> = []; build() { Row() { Column() { Button() { Text('photo') .fontSize(30) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 20 }) .backgroundColor('#0D9FFB') .width('40%') .height('5%') .onClick(() => { let resMgr = this.getUIContext()?.getHostContext()?.getApplicationContext().resourceManager; resMgr?.getRawFileContent(this.modelName).then(modelBuffer => { // Obtain images in an album. // 1. Create an image picker instance. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); // 2. Set the media file type to IMAGE and set the maximum number of media files that can be selected. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; photoSelectOptions.maxSelectNumber = 1; // 3. Create an album picker instance and call select() to open the album page for file selection. After file selection is done, the result set is returned through photoSelectResult. let photoPicker = new photoAccessHelper.PhotoViewPicker(); photoPicker.select(photoSelectOptions, async ( err: BusinessError, photoSelectResult: photoAccessHelper.PhotoSelectResult) => { if (err) { console.error('MS_LITE_ERR: PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('MS_LITE_LOG: PhotoViewPicker.select successfully, ' + 'photoSelectResult uri: ' + JSON.stringify(photoSelectResult)); this.uris = photoSelectResult.photoUris; console.info('MS_LITE_LOG: uri: ' + this.uris); // Preprocess the image data. try { // 1. Based on the specified URI, call fileIo.openSync to open the file to obtain the FD. let file = fileIo.openSync(this.uris[0], fileIo.OpenMode.READ_ONLY); console.info('MS_LITE_LOG: file fd: ' + file.fd); // 2. Based on the FD, call fileIo.readSync to read the data in the file. let inputBuffer = new ArrayBuffer(4096000); let readLen = fileIo.readSync(file.fd, inputBuffer); console.info('MS_LITE_LOG: readSync data to file succeed and inputBuffer size is:' + readLen); // 3. Perform image preprocessing through PixelMap. let imageSource = image.createImageSource(file.fd); imageSource.createPixelMap().then((pixelMap) => { pixelMap.getImageInfo().then((info) => { console.info('MS_LITE_LOG: info.width = ' + info.size.width); console.info('MS_LITE_LOG: info.height = ' + info.size.height); // 4. Crop the image based on the input image size and obtain the image buffer readBuffer. pixelMap.scale(256.0 / info.size.width, 256.0 / info.size.height).then(() => { pixelMap.crop( { x: 16, y: 16, size: { height: this.modelInputHeight, width: this.modelInputWidth } } ).then(async () => { let info = await pixelMap.getImageInfo(); console.info('MS_LITE_LOG: crop info.width = ' + info.size.width); console.info('MS_LITE_LOG: crop info.height = ' + info.size.height); // Set the size of readBuffer. let readBuffer = new ArrayBuffer(this.modelInputHeight * this.modelInputWidth * 4); await pixelMap.readPixelsToBuffer(readBuffer); console.info('MS_LITE_LOG: Succeeded in reading image pixel data, buffer: ' + readBuffer.byteLength); // Convert readBuffer to the float32 format, and standardize the image. const imageArr = new Uint8Array( readBuffer.slice(0, this.modelInputHeight * this.modelInputWidth * 4)); console.info('MS_LITE_LOG: imageArr length: ' + imageArr.length); let means = [0.485, 0.456, 0.406]; let stds = [0.229, 0.224, 0.225]; let float32View = new Float32Array(this.modelInputHeight * this.modelInputWidth * 3); let index = 0; for (let i = 0; i < imageArr.length; i++) { if ((i + 1) % 4 == 0) { float32View[index] = (imageArr[i - 3] / 255.0 - means[0]) / stds[0]; // B float32View[index+1] = (imageArr[i - 2] / 255.0 - means[1]) / stds[1]; // G float32View[index+2] = (imageArr[i - 1] / 255.0 - means[2]) / stds[2]; // R index += 3; } } console.info('MS_LITE_LOG: float32View length: ' + float32View.length); let printStr = 'float32View data:'; for (let i = 0; i < 20; i++) { printStr += ' ' + float32View[i]; } console.info('MS_LITE_LOG: float32View data: ' + printStr); }) }) }) }) } catch (err) { console.error('MS_LITE_LOG: uri: open file fd failed.' + err); } }) }) }) } .width('100%') } .height('100%') } }
application-dev\ai\mindspore\mindspore-guidelines-based-js.md
// model.ets import { mindSporeLite } from '@kit.MindSporeLiteKit' export default async function modelPredict( modelBuffer: ArrayBuffer, inputsBuffer: ArrayBuffer[]): Promise<mindSporeLite.MSTensor[]> { // 1. Create a context, and set parameters such as the number of runtime threads and device type. The context.target = ["nnrt"] option is not supported. let context: mindSporeLite.Context = {}; context.target = ['cpu']; context.cpu = {} context.cpu.threadNum = 2; context.cpu.threadAffinityMode = 1; context.cpu.precisionMode = 'enforce_fp32'; // 2. Load the model from the memory. let msLiteModel: mindSporeLite.Model = await mindSporeLite.loadModelFromBuffer(modelBuffer, context); // 3. Set the input data. let modelInputs: mindSporeLite.MSTensor[] = msLiteModel.getInputs(); for (let i = 0; i < inputsBuffer.length; i++) { let inputBuffer = inputsBuffer[i]; if (inputBuffer != null) { modelInputs[i].setData(inputBuffer as ArrayBuffer); } } // 4. Perform inference. console.info('=========MS_LITE_LOG: MS_LITE predict start====='); let modelOutputs: mindSporeLite.MSTensor[] = await msLiteModel.predict(modelInputs); return modelOutputs; }
application-dev\ai\mindspore\mindspore-guidelines-based-js.md
// Index.ets import modelPredict from './model'; @Entry @Component struct Index { @State modelName: string = 'mobilenetv2.ms'; @State modelInputHeight: number = 224; @State modelInputWidth: number = 224; @State max: number = 0; @State maxIndex: number = 0; @State maxArray: Array<number> = []; @State maxIndexArray: Array<number> = []; build() { Row() { Column() { Button() { Text('photo') .fontSize(30) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 20 }) .backgroundColor('#0D9FFB') .width('40%') .height('5%') .onClick(() => { let resMgr = this.getUIContext()?.getHostContext()?.getApplicationContext().resourceManager; resMgr?.getRawFileContent(this.modelName).then(modelBuffer => { let float32View = new Float32Array(this.modelInputHeight * this.modelInputWidth * 3); // Image input and preprocessing // The buffer data of the input image is stored in float32View after preprocessing. For details, see Image Input and Preprocessing. let inputs: ArrayBuffer[] = [float32View.buffer]; // predict modelPredict(modelBuffer.buffer.slice(0), inputs).then(outputs => { console.info('=========MS_LITE_LOG: MS_LITE predict success====='); // Print the result. for (let i = 0; i < outputs.length; i++) { let out = new Float32Array(outputs[i].getData()); let printStr = outputs[i].name + ':'; for (let j = 0; j < out.length; j++) { printStr += out[j].toString() + ','; } console.info('MS_LITE_LOG: ' + printStr); // Obtain the maximum number of categories. this.max = 0; this.maxIndex = 0; this.maxArray = []; this.maxIndexArray = []; let newArray = out.filter(value => value !== this.max) for (let n = 0; n < 5; n++) { this.max = out[0]; this.maxIndex = 0; for (let m = 0; m < newArray.length; m++) { if (newArray[m] > this.max) { this.max = newArray[m]; this.maxIndex = m; } } this.maxArray.push(Math.round(this.max * 10000)) this.maxIndexArray.push(this.maxIndex) // Call the array filter function. newArray = newArray.filter(value => value !== this.max) } console.info('MS_LITE_LOG: max:' + this.maxArray); console.info('MS_LITE_LOG: maxIndex:' + this.maxIndexArray); } console.info('=========MS_LITE_LOG END========='); }) }) }) } .width('100%') } .height('100%') } }
application-dev\ai\mindspore\mindspore-guidelines-based-native.md
// Index.ets import { fileIo } from '@kit.CoreFileKit'; import { photoAccessHelper } from '@kit.MediaLibraryKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { image } from '@kit.ImageKit'; @Entry @Component struct Index { @State modelName: string = 'mobilenetv2.ms'; @State modelInputHeight: number = 224; @State modelInputWidth: number = 224; @State uris: Array<string> = []; build() { Row() { Column() { Button() { Text('photo') .fontSize(30) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 20 }) .backgroundColor('#0D9FFB') .width('40%') .height('5%') .onClick(() => { let resMgr = this.getUIContext()?.getHostContext()?.getApplicationContext().resourceManager; // Obtain images in an album. // 1. Create an image picker instance. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); // 2. Set the media file type to IMAGE and set the maximum number of media files that can be selected. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; photoSelectOptions.maxSelectNumber = 1; // 3. Create an album picker instance and call select() to open the album page for file selection. After file selection is done, the result set is returned through photoSelectResult. let photoPicker = new photoAccessHelper.PhotoViewPicker(); photoPicker.select(photoSelectOptions, async (err: BusinessError, photoSelectResult: photoAccessHelper.PhotoSelectResult) => { if (err) { console.error('MS_LITE_ERR: PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('MS_LITE_LOG: PhotoViewPicker.select successfully, photoSelectResult uri: ' + JSON.stringify(photoSelectResult)); this.uris = photoSelectResult.photoUris; console.info('MS_LITE_LOG: uri: ' + this.uris); // Preprocess the image data. try { // 1. Based on the specified URI, call fileIo.openSync to open the file to obtain the FD. let file = fileIo.openSync(this.uris[0], fileIo.OpenMode.READ_ONLY); console.info('MS_LITE_LOG: file fd: ' + file.fd); // 2. Based on the FD, call fileIo.readSync to read the data in the file. let inputBuffer = new ArrayBuffer(4096000); let readLen = fileIo.readSync(file.fd, inputBuffer); console.info('MS_LITE_LOG: readSync data to file succeed and inputBuffer size is:' + readLen); // 3. Perform image preprocessing through PixelMap. let imageSource = image.createImageSource(file.fd); imageSource.createPixelMap().then((pixelMap) => { pixelMap.getImageInfo().then((info) => { console.info('MS_LITE_LOG: info.width = ' + info.size.width); console.info('MS_LITE_LOG: info.height = ' + info.size.height); // 4. Crop the image based on the input image size and obtain the image buffer readBuffer. pixelMap.scale(256.0 / info.size.width, 256.0 / info.size.height).then(() => { pixelMap.crop({ x: 16, y: 16, size: { height: this.modelInputHeight, width: this.modelInputWidth } }) .then(async () => { let info = await pixelMap.getImageInfo(); console.info('MS_LITE_LOG: crop info.width = ' + info.size.width); console.info('MS_LITE_LOG: crop info.height = ' + info.size.height); // Set the size of readBuffer. let readBuffer = new ArrayBuffer(this.modelInputHeight * this.modelInputWidth * 4); await pixelMap.readPixelsToBuffer(readBuffer); console.info('MS_LITE_LOG: Succeeded in reading image pixel data, buffer: ' + readBuffer.byteLength); // Convert readBuffer to the float32 format, and standardize the image. const imageArr = new Uint8Array(readBuffer.slice(0, this.modelInputHeight * this.modelInputWidth * 4)); console.info('MS_LITE_LOG: imageArr length: ' + imageArr.length); let means = [0.485, 0.456, 0.406]; let stds = [0.229, 0.224, 0.225]; let float32View = new Float32Array(this.modelInputHeight * this.modelInputWidth * 3); let index = 0; for (let i = 0; i < imageArr.length; i++) { if ((i + 1) % 4 == 0) { float32View[index] = (imageArr[i - 3] / 255.0 - means[0]) / stds[0]; // B float32View[index+1] = (imageArr[i - 2] / 255.0 - means[1]) / stds[1]; // G float32View[index+2] = (imageArr[i - 1] / 255.0 - means[2]) / stds[2]; // R index += 3; } } console.info('MS_LITE_LOG: float32View length: ' + float32View.length); let printStr = 'float32View data:'; for (let i = 0; i < 20; i++) { printStr += ' ' + float32View[i]; } console.info('MS_LITE_LOG: float32View data: ' + printStr); }) }) }) }) } catch (err) { console.error('MS_LITE_LOG: uri: open file fd failed.' + err); } }) }) }.width('100%') } .height('100%') } }
application-dev\ai\mindspore\mindspore-guidelines-based-native.md
export const runDemo: (a: number[], b:Object) => Array<number>;
application-dev\ai\mindspore\mindspore-guidelines-based-native.md
// Index.ets import msliteNapi from 'libentry.so' @Entry @Component struct Index { @State modelInputHeight: number = 224; @State modelInputWidth: number = 224; @State max: number = 0; @State maxIndex: number = 0; @State maxArray: Array<number> = []; @State maxIndexArray: Array<number> = []; build() { Row() { Column() { Button() { Text('photo') .fontSize(30) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 20 }) .backgroundColor('#0D9FFB') .width('40%') .height('5%') .onClick(() => { let resMgr = this.getUIContext()?.getHostContext()?.getApplicationContext().resourceManager; let float32View = new Float32Array(this.modelInputHeight * this.modelInputWidth * 3); // Image input and preprocessing // Call the C++ runDemo function. The buffer data of the input image is stored in float32View after preprocessing. For details, see Image Input and Preprocessing. console.info('MS_LITE_LOG: *** Start MSLite Demo ***'); let output: Array<number> = msliteNapi.runDemo(Array.from(float32View), resMgr); // Obtain the maximum number of categories. this.max = 0; this.maxIndex = 0; this.maxArray = []; this.maxIndexArray = []; let newArray = output.filter(value => value !== this.max); for (let n = 0; n < 5; n++) { this.max = output[0]; this.maxIndex = 0; for (let m = 0; m < newArray.length; m++) { if (newArray[m] > this.max) { this.max = newArray[m]; this.maxIndex = m; } } this.maxArray.push(Math.round(this.max * 10000)); this.maxIndexArray.push(this.maxIndex); // Call the array filter function. newArray = newArray.filter(value => value !== this.max); } console.info('MS_LITE_LOG: max:' + this.maxArray); console.info('MS_LITE_LOG: maxIndex:' + this.maxIndexArray); console.info('MS_LITE_LOG: *** Finished MSLite Demo ***'); }) }.width('100%') } .height('100%') } }
application-dev\application-models\ability-exit-info-record.md
import { UIAbility, Want, AbilityConstant } from '@kit.AbilityKit'; const MAX_RSS_THRESHOLD: number = 100000; const MAX_PSS_THRESHOLD: number = 100000; function doSomething() { console.log('do Something'); } function doAnotherThing() { console.log('do Another Thing'); } class MyAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { // Obtain the exit reason. let reason: number = launchParam.lastExitReason; let subReason: number = -1; if (launchParam.lastExitDetailInfo) { subReason = launchParam.lastExitDetailInfo.exitSubReason; } let exitMsg: string = launchParam.lastExitMessage; if (launchParam.lastExitDetailInfo) { // Obtain the information about the process where the ability was running before it exited. let pid = launchParam.lastExitDetailInfo.pid; let processName: string = launchParam.lastExitDetailInfo.processName; let rss: number = launchParam.lastExitDetailInfo.rss; let pss: number = launchParam.lastExitDetailInfo.pss; // Obtain other information. let uid: number = launchParam.lastExitDetailInfo.uid; let timestamp: number = launchParam.lastExitDetailInfo.timestamp; } } }
application-dev\application-models\ability-exit-info-record.md
if (reason === AbilityConstant.LastExitReason.APP_FREEZE) { // The ability exited last time due to no response. Add processing logic here. doSomething(); } else if (reason === AbilityConstant.LastExitReason.SIGNAL && subReason === 9) { // The ability exited last time because the process is terminated by the kill -9 signal. Add processing logic here. doAnotherThing(); } else if (reason === AbilityConstant.LastExitReason.RESOURCE_CONTROL) { // The ability exited last time due to RSS control last time. Implement the processing logic here. The simplest approach is to print the information. console.log('The ability has exit last because the rss control, the lastExitReason is '+ reason + ', subReason is ' + subReason + ', lastExitMessage is ' + exitMsg); }
application-dev\application-models\ability-exit-info-record.md
if (rss > MAX_RSS_THRESHOLD || pss > MAX_PSS_THRESHOLD) { // If the RSS or PSS value is too high, the memory usage is close to or has reached the upper limit. Print a warning or add processing logic. console.warn('Process ' + processName + '(' + pid + ') memory usage approaches or reaches the upper limit.'); }
application-dev\application-models\ability-exit-info-record.md
console.log('App ' + uid + ' terminated at ' + timestamp);
application-dev\application-models\ability-recover-guideline.md
import { UIAbility } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate() { console.info("[Demo] EntryAbility onCreate"); this.context.setRestoreEnabled(true); } }
application-dev\application-models\ability-recover-guideline.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.info("[Demo] EntryAbility onCreate"); this.context.setRestoreEnabled(true); if (want && want.parameters) { let recoveryMyData = want.parameters["myData"]; } } onSaveState(state:AbilityConstant.StateType, wantParams: Record<string, Object>) { // Ability has called to save app data console.log("[Demo] EntryAbility onSaveState"); wantParams["myData"] = "my1234567"; return AbilityConstant.OnSaveResult.ALL_AGREE; } }
application-dev\application-models\abilitystage.md
import { AbilityStage, Want } from '@kit.AbilityKit'; export default class MyAbilityStage extends AbilityStage { onCreate(): void { // This callback is triggered when the HAP is loaded for the first time. In this callback, you can initialize the module (for example, pre-load resources and create threads). } onAcceptWant(want: Want): string { // Triggered only for the UIAbility with the specified launch type. return 'MyAbilityStage'; } }
application-dev\application-models\abilitystage.md
import { EnvironmentCallback, AbilityStage } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; export default class MyAbilityStage extends AbilityStage { onCreate(): void { console.log('AbilityStage onCreate'); let envCallback: EnvironmentCallback = { onConfigurationUpdated(config) { console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`); let language = config.language; // Current language of the application. let colorMode = config.colorMode; // Dark/Light mode. let direction = config.direction; // Screen orientation. let fontSizeScale = config.fontSizeScale; // Font size scaling factor. let fontWeightScale = config.fontWeightScale; // Font weight scaling factor. }, onMemoryLevel(level) { console.log(`onMemoryLevel level: ${level}`); } }; try { let applicationContext = this.context.getApplicationContext(); let callbackId = applicationContext.on('environment', envCallback); console.log(`callbackId: ${callbackId}`); } catch (paramError) { console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`); } } onDestroy(): void { // Use onDestroy() to listen for the ability destruction event. console.log('AbilityStage onDestroy'); } }
application-dev\application-models\access-dataability.md
import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; import ability from '@ohos.ability.ability'; // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), three slashes in total. let uri: string = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(uri);
application-dev\application-models\access-dataability.md
import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; let valuesBucket_insert: rdb.ValuesBucket = { name: 'Rose', introduction: 'insert' }; let valuesBucket_update: rdb.ValuesBucket = { name: 'Rose', introduction: 'update' }; let crowd = new Array({ name: 'Rose', introduction: 'batchInsert_one' } as rdb.ValuesBucket, { name: 'Rose', introduction: 'batchInsert_two' } as rdb.ValuesBucket); let columnArray = new Array('id', 'name', 'introduction'); let predicates = new ohos_data_ability.DataAbilityPredicates();
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; // Callback mode: const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private valuesBucket_insert: rdb.ValuesBucket = { name: 'Rose', introduction: 'insert' }; private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Callback mode: this.DAHelper.insert(this.uri, this.valuesBucket_insert, (error: BusinessError, data: number) => { if (error && error.code !== 0) { promptAction.showToast({ message: 'insert_failed_toast' }); } else { promptAction.showToast({ message: 'insert_success_toast' }); } hilog.info(domain, TAG, 'DAHelper insert result: ' + data + ', error: ' + JSON.stringify(error)); } ); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private valuesBucket_insert: rdb.ValuesBucket = { name: 'Rose', introduction: 'insert' }; private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Promise mode (await needs to be used in the asynchronous method): this.DAHelper.insert(this.uri, this.valuesBucket_insert).then((datainsert) => { promptAction.showToast({ message: 'insert_success_toast' }); hilog.info(domain, TAG, 'DAHelper insert result: ' + datainsert); }).catch((error: BusinessError) => { promptAction.showToast({ message: 'insert_failed_toast' }); hilog.error(domain, TAG, `DAHelper insert failed. Cause: ${error.message}`); }); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private predicates = new ohos_data_ability.DataAbilityPredicates(); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Callback mode: this.DAHelper.delete(this.uri, this.predicates, (error, data) => { if (error && error.code !== 0) { promptAction.showToast({ message: 'delete_failed_toast' }); } else { promptAction.showToast({ message: 'delete_success_toast' }); } hilog.info(domain, TAG, 'DAHelper delete result: ' + data + ', error: ' + JSON.stringify(error)); } ); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private predicates = new ohos_data_ability.DataAbilityPredicates(); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Promise mode (await needs to be used in the asynchronous method): this.DAHelper.delete(this.uri, this.predicates).then((datadelete) => { promptAction.showToast({ message: 'delete_success_toast' }); hilog.info(domain, TAG, 'DAHelper delete result: ' + datadelete); }).catch((error: BusinessError) => { promptAction.showToast({ message: 'delete_failed_toast' }); hilog.error(domain, TAG, `DAHelper delete failed. Cause: ${error.message}`); }); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private valuesBucket_update: rdb.ValuesBucket = { name: 'Rose', introduction: 'update' }; private predicates = new ohos_data_ability.DataAbilityPredicates(); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Callback mode: this.predicates.equalTo('name', 'Rose'); this.DAHelper.update(this.uri, this.valuesBucket_update, this.predicates, (error, data) => { if (error && error.code !== 0) { promptAction.showToast({ message: 'update_failed_toast' }); } else { promptAction.showToast({ message: 'update_success_toast' }); } hilog.info(domain, TAG, 'DAHelper update result: ' + data + ', error: ' + JSON.stringify(error)); } ); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private valuesBucket_update: rdb.ValuesBucket = { name: 'Rose', introduction: 'update' }; private predicates = new ohos_data_ability.DataAbilityPredicates(); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Promise mode (await needs to be used in the asynchronous method): this.predicates.equalTo('name', 'Rose'); this.DAHelper.update(this.uri, this.valuesBucket_update, this.predicates).then((dataupdate) => { promptAction.showToast({ message: 'update_success_toast' }); hilog.info(domain, TAG, 'DAHelper update result: ' + dataupdate); }).catch((error: BusinessError) => { promptAction.showToast({ message: 'update_failed_toast' }); hilog.error(domain, TAG, `DAHelper update failed. Cause: ${error.message}`); }); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private columnArray = new Array('id', 'name', 'introduction'); private predicates = new ohos_data_ability.DataAbilityPredicates(); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Callback mode: this.predicates.equalTo('name', 'Rose'); this.DAHelper.query(this.uri, this.columnArray, this.predicates, (error, data) => { if (error && error.code !== 0) { promptAction.showToast({ message: 'query_failed_toast' }); hilog.error(domain, TAG, `DAHelper query failed. Cause: ${error.message}`); } else { promptAction.showToast({ message: 'query_success_toast' }); } // ResultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. while (data.goToNextRow()) { const id = data.getLong(data.getColumnIndex('id')); const name = data.getString(data.getColumnIndex('name')); const introduction = data.getString(data.getColumnIndex('introduction')); hilog.info(domain, TAG, `DAHelper query result:id = [${id}], name = [${name}], introduction = [${introduction}]`); } // Release the data set memory. data.close(); } ); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private columnArray = new Array('id', 'name', 'introduction'); private predicates = new ohos_data_ability.DataAbilityPredicates(); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Promise mode (await needs to be used in the asynchronous method): this.predicates.equalTo('name', 'Rose'); this.DAHelper.query(this.uri, this.columnArray, this.predicates).then((dataquery) => { promptAction.showToast({ message: 'query_success_toast' }); // ResultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. while (dataquery.goToNextRow()) { const id = dataquery.getLong(dataquery.getColumnIndex('id')); const name = dataquery.getString(dataquery.getColumnIndex('name')); const introduction = dataquery.getString(dataquery.getColumnIndex('introduction')); hilog.info(domain, TAG, `DAHelper query result:id = [${id}], name = [${name}], introduction = [${introduction}]`); } // Release the data set memory. dataquery.close(); }).catch((error: BusinessError) => { promptAction.showToast({ message: 'query_failed_toast' }); hilog.error(domain, TAG, `DAHelper query failed. Cause: ${error.message}`); }); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private crowd = new Array({ name: 'Rose', introduction: 'batchInsert_one' } as rdb.ValuesBucket, { name: 'Rose', introduction: 'batchInsert_two' } as rdb.ValuesBucket); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Callback mode: this.DAHelper.batchInsert(this.uri, this.crowd, (error, data) => { if (error && error.code !== 0) { promptAction.showToast({ message: 'batchInsert_failed_toast' }); } else { promptAction.showToast({ message: 'batchInsert_success_toast' }); } hilog.info(domain, TAG, 'DAHelper batchInsert result: ' + data + ', error: ' + JSON.stringify(error)); } ); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private crowd = new Array({ name: 'Rose', introduction: 'batchInsert_one' } as rdb.ValuesBucket, { name: 'Rose', introduction: 'batchInsert_two' } as rdb.ValuesBucket); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Promise mode (await needs to be used in the asynchronous method): this.DAHelper.batchInsert(this.uri, this.crowd).then((databatchInsert) => { promptAction.showToast({ message: 'batchInsert_success_toast' }); hilog.info(domain, TAG, 'DAHelper batchInsert result: ' + databatchInsert); }).catch((error: BusinessError) => { promptAction.showToast({ message: 'batchInsert_failed_toast' }); hilog.error(domain, TAG, `DAHelper batchInsert failed. Cause: ${error.message}`); }); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private predicates = new ohos_data_ability.DataAbilityPredicates(); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Callback mode: let operations: Array<ability.DataAbilityOperation> = [{ uri: this.uri, type: featureAbility.DataAbilityOperationType.TYPE_INSERT, valuesBucket: { name: 'Rose', introduction: 'executeBatch' }, predicates: this.predicates, expectedCount: 0, predicatesBackReferences: undefined, interrupted: true, }]; this.DAHelper.executeBatch(this.uri, operations, (error, data) => { if (error && error.code !== 0) { promptAction.showToast({ message: 'executeBatch_failed_toast' }); } else { promptAction.showToast({ message: 'executeBatch_success_toast' }); } hilog.info(domain, TAG, `DAHelper executeBatch, result: ` + JSON.stringify(data) + ', error: ' + JSON.stringify(error)); }); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\access-dataability.md
import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; import ohos_data_ability from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PageDataAbility'; const domain: number = 0xFF00; @Entry @Component struct PageDataAbility { private predicates = new ohos_data_ability.DataAbilityPredicates(); private uri = 'dataability:///com.samples.famodelabilitydevelop.DataAbility'; private DAHelper = featureAbility.acquireDataAbilityHelper(this.uri); build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItemGroup() { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { // ... } .onClick(() => { // Promise mode (await needs to be used in the asynchronous method): let operations: Array<ability.DataAbilityOperation> = [{ uri: this.uri, type: featureAbility.DataAbilityOperationType.TYPE_INSERT, valuesBucket: { name: 'Rose', introduction: 'executeBatch' }, predicates: this.predicates, expectedCount: 0, predicatesBackReferences: undefined, interrupted: true, }]; this.DAHelper.executeBatch(this.uri, operations).then((dataquery) => { promptAction.showToast({ message: 'executeBatch_success_toast' }); hilog.info(domain, TAG, 'DAHelper executeBatch result: ' + JSON.stringify(dataquery)); }).catch((error: BusinessError) => { promptAction.showToast({ message: 'executeBatch_failed_toast' }); hilog.error(domain, TAG, `DAHelper executeBatch failed. Cause: ${error.message}`); }); }) } // ... } // ... } // ... } // ... } }
application-dev\application-models\api-switch-overview.md
import featureAbility from '@ohos.ability.featureAbility'; import Want from '@ohos.app.ability.Want'; import hilog from '@ohos.hilog'; const TAG: string = 'PagePageAbilityFirst'; const domain: number = 0xFF00; @Entry @Component struct PagePageAbilityFirst { build() { Column() { List({ initialIndex: 0 }) { ListItem() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) { //... } .onClick(() => { (async (): Promise<void> => { try { hilog.info(domain, TAG, 'Begin to start ability'); let want: Want = { bundleName: 'com.samples.famodelabilitydevelop', moduleName: 'entry', abilityName: 'com.samples.famodelabilitydevelop.PageAbilitySingleton' }; await featureAbility.startAbility({ want: want }); hilog.info(domain, TAG, `Start ability succeed`); } catch (error) { hilog.error(domain, TAG, 'Start ability failed with ' + error); } })() }) } //... } //... } //... } }
application-dev\application-models\api-switch-overview.md
import { hilog } from '@kit.PerformanceAnalysisKit'; import { Want, common, Caller } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Page_UIAbilityComponentsInteractive]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_UIAbilityComponentsInteractive { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; caller: Caller | undefined = undefined; build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { // Context is a member of the ability object and is required for invoking inside a non-ability object. // Pass in the Context object. let wantInfo: Want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.samples.stagemodelabilitydevelop', moduleName: 'entry', // moduleName is optional. abilityName: 'FuncAbilityA', parameters: { // Custom information. info: 'From the UIAbilityComponentsInteractive page of EntryAbility', }, }; // context is the UIAbilityContext of the initiator UIAbility. this.context.startAbility(wantInfo).then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'startAbility success.'); }).catch((error: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, 'startAbility failed.'); }); }) } //... } //... } //... } }
application-dev\application-models\app-linking-startup.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { url } from '@kit.ArkTS'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // Obtain the input link information from want. // For example, the input URL is https://www.example.com/programs?action=showall. let uri = want?.uri if (uri) { // Parse the query parameter from the link. You can perform subsequent processing based on service requirements. let urlObject = url.URL.parseURL(want?.uri); let action = urlObject.params.get('action') // For example, if action is set to showall, all programs are displayed. if (action === "showall") { // ... } } } }
application-dev\application-models\app-linking-startup.md
import common from '@ohos.app.ability.common'; import { BusinessError } from '@ohos.base'; @Entry @Component struct Index { build() { Button('start link', { type: ButtonType.Capsule, stateEffect: true }) .width('87%') .height('5%') .margin({ bottom: '12vp' }) .onClick(() => { let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; let link: string = "https://www.example.com/programs?action=showall"; // Open the application only in App Linking mode. context.openLink(link, { appLinkingOnly: true }) .then(() => { console.info('openlink success.'); }) .catch((error: BusinessError) => { console.error(`openlink failed. error:${JSON.stringify(error)}`); }); }) } }
application-dev\application-models\app-startup.md
import { StartupConfig, StartupConfigEntry, StartupListener } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; export default class MyStartupConfigEntry extends StartupConfigEntry { onConfig() { hilog.info(0x0000, 'testTag', `onConfig`); let onCompletedCallback = (error: BusinessError<void>) => { hilog.info(0x0000, 'testTag', `onCompletedCallback`); if (error) { hilog.error(0x0000, 'testTag', 'onCompletedCallback: %{public}d, message: %{public}s', error.code, error.message); } else { hilog.info(0x0000, 'testTag', `onCompletedCallback: success.`); } }; let startupListener: StartupListener = { 'onCompleted': onCompletedCallback }; let config: StartupConfig = { 'timeoutMs': 10000, 'startupListener': startupListener }; return config; } }
application-dev\application-models\app-startup.md
import { StartupTask, common } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; @Sendable export default class StartupTask_001 extends StartupTask { constructor() { super(); } async init(context: common.AbilityStageContext) { hilog.info(0x0000, 'testTag', 'StartupTask_001 init.'); return 'StartupTask_001'; } onDependencyCompleted(dependence: string, result: Object): void { hilog.info(0x0000, 'testTag', 'StartupTask_001 onDependencyCompleted, dependence: %{public}s, result: %{public}s', dependence, JSON.stringify(result)); } }
application-dev\application-models\app-startup.md
import { AbilityConstant, UIAbility, Want, startupManager } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); let startParams = ['StartupTask_005', 'StartupTask_006']; try { startupManager.run(startParams).then(() => { console.log(`StartupTest startupManager run then, startParams = ${JSON.stringify(startParams)}.`); }).catch((error: BusinessError) => { console.error(`StartupTest promise catch error, error = ${JSON.stringify(error)}.`); console.error(`StartupTest promise catch error, startParams = ${JSON.stringify(startParams)}.`); }) } catch (error) { let errMsg = (error as BusinessError).message; let errCode = (error as BusinessError).code; console.error(`Startup catch error, errCode= ${errCode}.`); console.error(`Startup catch error, errMsg= ${errMsg}.`); } } // ... }
application-dev\application-models\app-startup.md
import { startupManager } from '@kit.AbilityKit'; @Entry @Component struct Index { @State message: string = "Manual Mode"; @State startParams1: Array<string> = ["StartupTask_006"]; @State startParams2: Array<string> = ["libentry_006"]; build() { RelativeContainer() { Button(this.message) .id('AppStartup') .fontSize(20) .fontWeight(FontWeight.Bold) .onClick(() => { if (!startupManager.isStartupTaskInitialized("StartupTask_006") ) { // Check whether the startup task finishes execution. startupManager.run(this.startParams1) } if (!startupManager.isStartupTaskInitialized("libentry_006") ) { startupManager.run(this.startParams2) } }) .alignRules({ center: {anchor: '__container__', align: VerticalAlign.Center}, middle: {anchor: '__container__', align: HorizontalAlign.Center} }) } .height('100%') .width('100%') } }
application-dev\application-models\application-context-fa.md
import featureAbility from '@ohos.ability.featureAbility';
application-dev\application-models\application-context-fa.md
import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext();
application-dev\application-models\application-context-fa.md
import featureAbility from '@ohos.ability.featureAbility'; import hilog from '@ohos.hilog'; const TAG: string = 'MainAbility'; const domain: number = 0xFF00; class MainAbility { onCreate() { // Obtain the context and call related APIs. let context = featureAbility.getContext(); context.getBundleName((data, bundleName) => { hilog.info(domain, TAG, 'ability bundleName:' + bundleName); }); hilog.info(domain, TAG, 'Application onCreate'); } //... } export default new MainAbility();
application-dev\application-models\application-context-fa.md
import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; import hilog from '@ohos.hilog'; const TAG: string = 'PageAbilitySingleton'; const domain: number = 0xFF00; class PageAbilitySingleton { onCreate() { // Obtain the context and call related APIs. let context = featureAbility.getContext(); context.setDisplayOrientation(bundle.DisplayOrientation.PORTRAIT).then(() => { hilog.info(domain, TAG, 'Set display orientation.'); }) hilog.info(domain, TAG, 'Application onCreate'); } onDestroy() { hilog.info(domain, TAG, 'Application onDestroy'); } //... } export default new PageAbilitySingleton();
application-dev\application-models\application-context-stage.md
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { let uiAbilityContext = this.context; //... } }
application-dev\application-models\application-context-stage.md
import { FormExtensionAbility, formBindingData } from '@kit.FormKit'; import { Want } from '@kit.AbilityKit'; export default class MyFormExtensionAbility extends FormExtensionAbility { onAddForm(want: Want) { let formExtensionContext = this.context; // ... let dataObj1: Record<string, string> = { 'temperature': '11c', 'time': '11:00' }; let obj1: formBindingData.FormBindingData = formBindingData.createFormBindingData(dataObj1); return obj1; } }
application-dev\application-models\application-context-stage.md
import { AbilityStage } from '@kit.AbilityKit'; export default class MyAbilityStage extends AbilityStage { onCreate(): void { let abilityStageContext = this.context; //... } }
application-dev\application-models\application-context-stage.md
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { let applicationContext = this.context.getApplicationContext(); //... } }
application-dev\application-models\application-context-stage.md
import { common } from '@kit.AbilityKit'; import { buffer } from '@kit.ArkTS'; import { fileIo, ReadOptions } from '@kit.CoreFileKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[Page_Context]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Index { @State message: string = 'Hello World'; private context = this.getUIContext().getHostContext() as common.UIAbilityContext; build() { Row() { Column() { Text(this.message) // ... Button() { Text('create file') // ... .onClick(() => { let applicationContext = this.context.getApplicationContext(); // Obtain the application file path. let filesDir = applicationContext.filesDir; hilog.info(DOMAIN_NUMBER, TAG, `filePath: ${filesDir}`); // Create and open the file if it does not exist. Open the file if it already exists. let file = fileIo.openSync(filesDir + '/test.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); // Write data to the file. let writeLen = fileIo.writeSync(file.fd, "Try to write str."); hilog.info(DOMAIN_NUMBER, TAG, `The length of str is: ${writeLen}`); // Create an ArrayBuffer object with a size of 1024 bytes to store the data read from the file. let arrayBuffer = new ArrayBuffer(1024); // Set the offset and length to read. let readOptions: ReadOptions = { offset: 0, length: arrayBuffer.byteLength }; // Read the file content to the ArrayBuffer object and return the number of bytes that are actually read. let readLen = fileIo.readSync(file.fd, arrayBuffer, readOptions); // Convert the ArrayBuffer object into a Buffer object and output it as a string. let buf = buffer.from(arrayBuffer, 0, readLen); hilog.info(DOMAIN_NUMBER, TAG, `the content of file: ${buf.toString()}`); // Close the file. fileIo.closeSync(file); }) } // ... } // ... } // ... } }
application-dev\application-models\application-context-stage.md
// EntryAbility.ets import { UIAbility, contextConstant, AbilityConstant, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { // Before storing common information, switch the encryption level to EL1. this.context.area = contextConstant.AreaMode.EL1; // Change the encryption level. // Store common information. // Before storing sensitive information, switch the encryption level to EL2. this.context.area = contextConstant.AreaMode.EL2; // Change the encryption level. // Store sensitive information. // Before storing sensitive information, switch the encryption level to EL3. this.context.area = contextConstant.AreaMode.EL3; // Change the encryption level. // Store sensitive information. // Before storing sensitive information, switch the encryption level to EL4. this.context.area = contextConstant.AreaMode.EL4; // Change the encryption level. // Store sensitive information. // Before storing sensitive information, switch the encryption level to EL5. this.context.area = contextConstant.AreaMode.EL5; // Change the encryption level. // Store sensitive information. } }
application-dev\application-models\application-context-stage.md
// Index.ets import { contextConstant, common } from '@kit.AbilityKit'; @Entry @Component struct Page_Context { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; build() { Column() { //... List({ initialIndex: 0 }) { //... ListItem() { Row() { //... } .onClick(() => { // Before storing common information, switch the encryption level to EL1. if (this.context.area === contextConstant.AreaMode.EL2) { // Obtain the encryption level. this.context.area = contextConstant.AreaMode.EL1; // Change the encryption level. this.getUIContext().getPromptAction().showToast({ message: 'SwitchToEL1' }); } // Store common information. }) } //... ListItem() { Row() { //... } .onClick(() => { // Before storing sensitive information, switch the encryption level to EL2. if (this.context.area === contextConstant.AreaMode.EL1) { // Obtain the encryption level. this.context.area = contextConstant.AreaMode.EL2; // Change the encryption level. this.getUIContext().getPromptAction().showToast({ message: 'SwitchToEL2' }); } // Store sensitive information. }) } //... } //... } //... } }
application-dev\application-models\application-context-stage.md
import { common, application } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; let storageEventCall = new LocalStorage(); @Entry(storageEventCall) @Component struct Page_Context { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { let moduleName2: string = 'entry'; application.createModuleContext(this.context, moduleName2) .then((data: common.Context) => { console.info(`CreateModuleContext success, data: ${JSON.stringify(data)}`); if (data !== null) { this.getUIContext().getPromptAction().showToast({ message: ('Context obtained') }); } }) .catch((err: BusinessError) => { console.error(`CreateModuleContext failed, err code:${err.code}, err msg: ${err.message}`); }); }) } //... } //... } //... } }
application-dev\application-models\application-context-stage.md
import { AbilityConstant, AbilityLifecycleCallback, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[LifecycleAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class LifecycleAbility extends UIAbility { // Define a lifecycle ID. lifecycleId: number = -1; onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // Define a lifecycle callback object. let abilityLifecycleCallback: AbilityLifecycleCallback = { // Called when a UIAbility is created. onAbilityCreate(uiAbility) { hilog.info(DOMAIN_NUMBER, TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when a window is created. onWindowStageCreate(uiAbility, windowStage: window.WindowStage) { hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the window becomes active. onWindowStageActive(uiAbility, windowStage: window.WindowStage) { hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the window becomes inactive. onWindowStageInactive(uiAbility, windowStage: window.WindowStage) { hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the window is destroyed. onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) { hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the UIAbility is destroyed. onAbilityDestroy(uiAbility) { hilog.info(DOMAIN_NUMBER, TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when the UIAbility is switched from the background to the foreground. onAbilityForeground(uiAbility) { hilog.info(DOMAIN_NUMBER, TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when the UIAbility is switched from the foreground to the background. onAbilityBackground(uiAbility) { hilog.info(DOMAIN_NUMBER, TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when UIAbility is continued on another device. onAbilityContinue(uiAbility) { hilog.info(DOMAIN_NUMBER, TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); } }; // Obtain the application context. let applicationContext = this.context.getApplicationContext(); try { // Register the application lifecycle callback. this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback); } catch (err) { let code = (err as BusinessError).code; let message = (err as BusinessError).message; hilog.error(DOMAIN_NUMBER, TAG, `Failed to register applicationContext. Code is ${code}, message is ${message}`); } hilog.info(DOMAIN_NUMBER, TAG, `register callback number: ${this.lifecycleId}`); } //... onDestroy(): void { // Obtain the application context. let applicationContext = this.context.getApplicationContext(); try { // Deregister the application lifecycle callback. applicationContext.off('abilityLifecycle', this.lifecycleId); } catch (err) { let code = (err as BusinessError).code; let message = (err as BusinessError).message; hilog.error(DOMAIN_NUMBER, TAG, `Failed to unregister applicationContext. Code is ${code}, message is ${message}`); } } }
application-dev\application-models\autofillextensionablility-guide.md
import { hilog } from '@kit.PerformanceAnalysisKit'; import { AutoFillExtensionAbility, autoFillManager, UIExtensionContentSession } from '@kit.AbilityKit'; class AutoFillAbility extends AutoFillExtensionAbility { // ... // The onFillRequest lifecycle callback is triggered when the auto-fill service initiates an auto-fill request. onFillRequest(session: UIExtensionContentSession, request: autoFillManager.FillRequest, callback: autoFillManager.FillRequestCallback) { hilog.info(0x0000, 'testTag', '%{public}s', 'autofill onFillRequest'); try { // Save the page data and callback data carried in onFillRequest. let obj: Record<string, UIExtensionContentSession | autoFillManager.FillRequestCallback | autoFillManager.ViewData> = { 'session': session, 'fillCallback': callback, // The auto-fill processing result is returned to the client through this callback. 'viewData': request.viewData, // Assemble the data to be populated to viewData and return the data to the client through the callback. }; let storageFill: LocalStorage = new LocalStorage(obj); // Load the auto-fill processing page. session.loadContent('autofillpages/AutoFillPassWord', storageFill); } catch (err) { hilog.error(0x0000, 'testTag', '%{public}s', 'autofill failed to load content'); } } // The onSaveRequest lifecycle callback is triggered when the auto-save service initiates an auto-save request. onSaveRequest(session: UIExtensionContentSession, request: autoFillManager.SaveRequest, callback: autoFillManager.SaveRequestCallback): void { hilog.info(0x0000, 'testTag', '%{public}s', 'autofill onSaveRequest'); try { let obj: Record<string, UIExtensionContentSession | autoFillManager.SaveRequestCallback | autoFillManager.ViewData> = { 'session': session, 'saveCallback': callback, // The auto-save processing result is returned to the client through this callback. 'viewData': request.viewData, // Assemble the data to be populated to viewData and return the data to the client through the callback. } // Save the page data and callback data carried in onSaveRequest. let storageSave: LocalStorage = new LocalStorage(obj); // Load the auto-save processing page. session.loadContent('autofillpages/SavePage', storageSave); } catch (err) { hilog.error(0x0000, 'testTag', '%{public}s', 'autofill failed'); } } }
application-dev\application-models\autofillextensionablility-guide.md
import { autoFillManager } from '@kit.AbilityKit'; // Assemble the data to be populated to viewData and use the onSuccess callback to return the data to the client for auto-fill. function successFunc(data: autoFillManager.ViewData, target: string, fillCallback?: autoFillManager.FillRequestCallback) { console.info(`data.pageNodeInfos.length`, data.pageNodeInfos.length); for (let i = 0; i < data.pageNodeInfos.length; i++) { console.info(`data.pageNodeInfos[i].isFocus`, data.pageNodeInfos[i].isFocus); if (data.pageNodeInfos[i].isFocus == true) { data.pageNodeInfos[i].value = target; break; } } if (fillCallback) { let response: autoFillManager.FillResponse = { viewData: data }; fillCallback.onSuccess(response); } } function failFunc(fillCallback?: autoFillManager.FillRequestCallback) { if (fillCallback) { fillCallback.onFailure(); } } function cancelFunc(fillContent?: string, fillCallback?: autoFillManager.FillRequestCallback) { if (fillCallback) { try { fillCallback.onCancel(fillContent); } catch (error) { console.error('fillContent undefined: ', JSON.stringify(error)); } } } @Entry @Component struct AutoFillControl { storage: LocalStorage | undefined = this.getUIContext().getSharedLocalStorage(); fillCallback: autoFillManager.FillRequestCallback | undefined = this.storage?.get<autoFillManager.FillRequestCallback>('fillCallback'); viewData: autoFillManager.ViewData | undefined = this.storage?.get<autoFillManager.ViewData>('viewData'); build() { Column() { Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Text('Select a saved account and password') .fontWeight(500) .fontFamily('HarmonyHeiTi-Medium') .fontSize(20) .fontColor('#000000') .margin({ left: '4.4%' }) }.margin({ top: '8.8%', left: '4.9%' }).height('7.2%') Row() { Column() { List({ space: 10, initialIndex: 0 }) { ListItem() { Text('15501212262') .width('100%') .height(40) .fontSize(16) .textAlign(TextAlign.Center) .borderRadius(5) } .onClick(() => { if (this.viewData != undefined) { // Populate the selected account and password in the client. successFunc(this.viewData, '15501212262', this.fillCallback); } }) } // ... .listDirection(Axis.Vertical) .scrollBar(BarState.Off) .friction(0.6) .divider({ strokeWidth: 1, color: '#fff5eeee', startMargin: 20, endMargin: 20 }) .edgeEffect(EdgeEffect.Spring) .onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => { console.info('first' + firstIndex) console.info('last' + lastIndex) console.info('center' + centerIndex) }) .onDidScroll((scrollOffset: number, scrollState: ScrollState) => { console.info(`onDidScroll scrollState = ScrollState` + scrollState + `scrollOffset = ` + scrollOffset) }) } .width('100%') .shadow(ShadowStyle.OUTER_FLOATING_SM) .margin({ top: 50 }) } Row() { Button("Cancel") .onClick(() => { // Call cancelFunc() to notify the client when auto-fill is canceled. cancelFunc(undefined, this.fillCallback); }) .margin({ top: 30, bottom: 10, left: 10, right: 10 }) Button("Failure") .onClick(() => { // Call failFunc() to notify the client that auto-fill fails when the account and password are not obtained. failFunc(this.fillCallback); }) .margin({ top: 30, bottom: 10, left: 10, right: 10 }) } .backgroundColor('#f1f3f5').height('100%') } } }
application-dev\application-models\autofillextensionablility-guide.md
import { autoFillManager } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; function SuccessFunc(success : boolean, saveRequestCallback?: autoFillManager.SaveRequestCallback) { if (saveRequestCallback) { if (success) { saveRequestCallback.onSuccess(); return; } saveRequestCallback.onFailure(); } hilog.error(0x0000, "testTag", "saveRequestCallback is nullptr!"); } @Entry @Component struct SavePage { @State message: string = 'Save Account?' storage: LocalStorage | undefined = this.getUIContext().getSharedLocalStorage(); saveRequestCallback: autoFillManager.SaveRequestCallback | undefined = this.storage?.get<autoFillManager.SaveRequestCallback>('saveCallback'); build() { Row() { Column() { Text(this.message) .fontSize(35) .fontWeight(FontWeight.Bold) Row() { // Call onSuccess() (upon the touch of the save button) to notify the client that the form data is saved successfully. Button("save") .type(ButtonType.Capsule) .fontSize(20) .margin({ top: 30, right: 30 }) .onClick(() => { SuccessFunc(true, this.saveRequestCallback); }) // Call onFailure() (upon the touch of the back button) to notify the client that the user cancels saving the form data or saving the form data fails. Button("back") .type(ButtonType.Capsule) .fontSize(20) .margin({ top: 30, left: 30 }) .onClick(() => { SuccessFunc(false, this.saveRequestCallback); }) } } .width('100%') } .height('100%') } }
application-dev\application-models\autofillextensionablility-guide.md
@Entry @Component struct Index { loginBtnColor: String = '#bfdbf9'; build() { Column() { Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Text('Welcome!') .fontSize(24) .fontWeight(500) .fontFamily('HarmonyHeiTi-Medium') .fontColor('#182431') }.margin({ top: '32.3%' }).width('35%').height('4.1%') // Add a text box of the account type. List() { ListItemGroup({ style: ListItemGroupStyle.CARD }) { ListItem({ style: ListItemStyle.CARD }) { TextInput({placeholder: 'Enter an account.'}) .type(InputType.USER_NAME) .fontFamily('HarmonyHeiTi') .fontColor('#182431') .fontWeight(400) .fontSize(16) .height('100%') .id('userName') .backgroundColor('#FFFFFF') .onChange((value: string) => { if (value) { this.loginBtnColor = '#007DFF'; } else { this.loginBtnColor = '#bfdbf9'; } }) .enableAutoFill(true) }.padding(0) // Add a text box of the password type. ListItem({ style: ListItemStyle.CARD }) { TextInput({placeholder: 'Enter the password.'}) .type(InputType.Password) .fontFamily('HarmonyHeiTi') .fontColor('#182431') .fontWeight(400) .fontSize(16) .height('100%') .backgroundColor('#FFFFFF') .id('passWord') .onChange((value: string) => { if (value) { this.loginBtnColor = '#007DFF'; } else { this.loginBtnColor = '#bfdbf9'; } }) .enableAutoFill(true) }.padding(0) } .backgroundColor('#FFFFFF') .divider({ strokeWidth: 0.5, color: '#f1f3f5', startMargin: 15, endMargin: 15 }) } .borderRadius(24) .width('93.3%') .height('16%') .margin({ top: '8.6%' }) } } }
application-dev\application-models\autofillextensionablility-guide.md
@Entry @Component struct Index { @State inputTxt: string = ''; build() { Column() { Column() { Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Text ('Scenario-specific population') .fontWeight(500) .fontFamily('HarmonyHeiTi-Medium') // ... } .margin({ top: '14.2%' }).height('7.2%') Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Column() { Row() { Text('Set the type.') .fontColor('#99000000') .fontSize(14) .fontWeight(400) .textAlign(TextAlign.Start) .width('91%') .margin({ top: 5, left: -7.5 }) } Row() { TextInput({ placeholder: 'Input content', text: this.inputTxt }) .contentType(ContentType.FULL_PHONE_NUMBER) // Scenario-specific automatic population .height('9.4%') .width('91%') .fontWeight(FontWeight.Bolder) .placeholderColor('#99000000') .backgroundColor('#ffffffff') .id('password1') .fontSize(16) .fontWeight(400) .borderStyle(BorderStyle.Solid) .enableAutoFill(true) .borderRadius(25) .margin({ top: '8vp' }) } }.margin({ top: '7.1%' }) } Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Column() { Row() { Text('Set the type to name') .fontColor('#99000000') .fontSize(14) .fontWeight(400) .textAlign(TextAlign.Start) .width('91%') .margin({ top: 5, left: -7.5 }) } Row() { TextInput({ placeholder: 'Name', text: this.inputTxt }) .contentType(ContentType.PERSON_FULL_NAME) // Scenario-specific automatic population .height('9.4%') .width('91%') .fontWeight(FontWeight.Bold) .placeholderColor('#99000000') .backgroundColor('#ffffffff') .fontSize(16) .fontWeight(400) .id('password3') .borderStyle(BorderStyle.Solid) .enableAutoFill(true) .borderRadius(25) .onChange(() => { }) .margin({ top: '8vp' }) } } } .margin({ top: '20vp' }) }.height('70%') } .backgroundColor('#ffffff').height('100%') } }
application-dev\application-models\bind-serviceability-from-stage.md
import { common, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[Page_StartFAModel]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_StartFAModel { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItem() { Row() { // ... } .onClick(() => { let want: Want = { bundleName: 'com.samples.famodelabilitydevelop', abilityName: 'com.samples.famodelabilitydevelop.ServiceAbility', }; let options: common.ConnectOptions = { onConnect: (elementName, proxy) => { hilog.info(DOMAIN_NUMBER, TAG, `onConnect called.`); this.getUIContext().getPromptAction().showToast({ message: 'ConnectFAServiceAbility' }); }, onDisconnect: (elementName) => { hilog.info(DOMAIN_NUMBER, TAG, `onDisconnect called.`); }, onFailed: (code) => { hilog.error(DOMAIN_NUMBER, TAG, `onFailed code is: ${code}.`); } }; let connectionId = this.context.connectServiceExtensionAbility(want, options); hilog.info(DOMAIN_NUMBER, TAG, `connectionId is: ${JSON.stringify(connectionId)}.`); }) } // ... } // ... } // ... } }
application-dev\application-models\bind-serviceability-from-stage.md
import { common, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[Page_StartFAModel]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_StartFAModel { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItem() { Row() { // ... } .onClick(() => { let want: Want = { bundleName: 'com.samples.famodelabilitydevelop', abilityName: 'com.samples.famodelabilitydevelop.ServiceAbility', }; let options: common.ConnectOptions = { onConnect: (elementName, proxy) => { hilog.info(DOMAIN_NUMBER, TAG, `onConnect called.`); this.getUIContext().getPromptAction().showToast({ message: 'ConnectFAServiceAbility' }); }, onDisconnect: (elementName) => { hilog.info(DOMAIN_NUMBER, TAG, `onDisconnect called.`); }, onFailed: (code) => { hilog.error(DOMAIN_NUMBER, TAG, `onFailed code is: ${code}.`); } }; let connectionId = this.context.connectServiceExtensionAbility(want, options); hilog.info(DOMAIN_NUMBER, TAG, `connectionId is: ${JSON.stringify(connectionId)}.`); }) } // ... } // ... } // ... } }
application-dev\application-models\bind-serviceextensionability-from-fa.md
import featureAbility from '@ohos.ability.featureAbility'; import common from '@ohos.app.ability.common'; import Want from '@ohos.app.ability.Want'; import { BusinessError } from '@ohos.base'; import hilog from '@ohos.hilog'; const TAG: string = 'PageInterflowFaAndStage'; const domain: number = 0xFF00; @Entry @Component struct PageInterflowFaAndStage { build() { Column() { // ... List({ initialIndex: 0 }) { ListItem() { Row() { // ... } .onClick(() => { let want: Want = { bundleName: 'ohos.samples.etsclock', abilityName: 'MainAbility' }; featureAbility.startAbility({ want }).then((code) => { hilog.info(domain, TAG, `Ability verify code: ${JSON.stringify(code)}.`); }).catch((error: BusinessError) => { hilog.error(domain, TAG, `Ability failed, error msg: ${JSON.stringify(error)}.`); }); let serviceWant: Want = { bundleName: 'com.samples.stagemodelabilityinteraction', abilityName: 'ServiceExtAbility' }; let faConnect: common.ConnectOptions = { onConnect: (elementName, proxy) => { hilog.info(domain, TAG, `FaConnection onConnect called.`); }, onDisconnect: (elementName) => { hilog.info(domain, TAG, `FaConnection onDisconnect called.`); }, onFailed: (code) => { hilog.error(domain, TAG, `FaConnection onFailed code is: ${code}`); } }; let connectionId = featureAbility.connectAbility(serviceWant, faConnect); }) } // ... } // ... } // ... } }
application-dev\application-models\bind-serviceextensionability-from-fa.md
import type common from '@ohos.app.ability.common'; import particleAbility from '@ohos.ability.particleAbility'; import type Want from '@ohos.app.ability.Want'; import type { BusinessError } from '@ohos.base'; import hilog from '@ohos.hilog'; const TAG: string = '[Sample_FAModelAbilityDevelop]'; const domain: number = 0xFF00; class ServiceAbilityStartUiAbility { onStart(): void { // Start the UIAbility. let want: Want = { bundleName: 'ohos.samples.etsclock', abilityName: 'MainAbility' }; particleAbility.startAbility({ want }).then(() => { hilog.info(domain, TAG, `ServiceAbilityStartUIAbility Start Ability successfully.`); }).catch((error: BusinessError) => { hilog.error(domain, TAG, `ServiceAbilityStartUIAbility Ability failed: ${JSON.stringify(error)}.`); }); // Access the ServiceExtensionAbility. let serviceWant: Want = { bundleName: 'com.samples.stagemodelabilityinteraction', abilityName: 'ServiceExtAbility' }; let faConnect: common.ConnectOptions = { onConnect: (elementName, proxy) => { hilog.info(domain, TAG, `FaConnection onConnect called.`); }, onDisconnect: (elementName) => { hilog.info(domain, TAG, `FaConnection onDisconnect called.`); }, onFailed: (code) => { hilog.error(domain, TAG, `FaConnection onFailed code is: ${code}.`); } }; let connectionId = particleAbility.connectAbility(serviceWant, faConnect); hilog.info(domain, TAG, `ServiceAbilityStartUIAbility ServiceAbility onStart.`); } }; export default new ServiceAbilityStartUiAbility();
application-dev\application-models\canopenlink.md
import { bundleManager } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; try { let link = 'app1Scheme://test.example.com/home'; let canOpen = bundleManager.canOpenLink(link); hilog.info(0x0000, 'testTag', 'canOpenLink successfully: %{public}s', JSON.stringify(canOpen)); } catch (err) { let message = (err as BusinessError).message; hilog.error(0x0000, 'testTag', 'canOpenLink failed: %{public}s', message); }
application-dev\application-models\connect-serviceability.md
import featureAbility from '@ohos.ability.featureAbility'; import common from '@ohos.app.ability.common'; import Want from '@ohos.app.ability.Want'; import promptAction from '@ohos.promptAction'; import rpc from '@ohos.rpc'; import hilog from '@ohos.hilog';
application-dev\application-models\connect-serviceability.md
const TAG: string = 'PageServiceAbility'; const domain: number = 0xFF00; @Entry @Component struct PageServiceAbility { //... build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { let option: common.ConnectOptions = { onConnect: (element, proxy) => { hilog.info(domain, TAG, `onConnectLocalService onConnectDone element:` + JSON.stringify(element)); if (proxy === null) { promptAction.showToast({ message: 'connect_service_failed_toast' }); return; } let data = rpc.MessageParcel.create(); let reply = rpc.MessageParcel.create(); let option = new rpc.MessageOption(); data.writeInterfaceToken('connect.test.token'); proxy.sendRequest(0, data, reply, option); promptAction.showToast({ message: 'connect_service_success_toast' }); }, onDisconnect: (element) => { hilog.info(domain, TAG, `onConnectLocalService onDisconnectDone element:${element}`); promptAction.showToast({ message: 'disconnect_service_success_toast' }); }, onFailed: (code) => { hilog.info(domain, TAG, `onConnectLocalService onFailed errCode:${code}`); promptAction.showToast({ message: 'connect_service_failed_toast' }); } }; let request: Want = { bundleName: 'com.samples.famodelabilitydevelop', abilityName: 'com.samples.famodelabilitydevelop.ServiceAbility', }; let connId = featureAbility.connectAbility(request, option); hilog.info(domain, TAG, `onConnectLocalService onFailed errCode:${connId}`); }) } //... } //... } //... } }
application-dev\application-models\connect-serviceability.md
import type Want from '@ohos.app.ability.Want'; import rpc from '@ohos.rpc'; import hilog from '@ohos.hilog'; const TAG: string = '[Sample_FAModelAbilityDevelop]'; const domain: number = 0xFF00; class FirstServiceAbilityStub extends rpc.RemoteObject { constructor(des: Object) { if (typeof des === 'string') { super(des); } else { return; } } onRemoteRequest(code: number, data: rpc.MessageParcel, reply: rpc.MessageParcel, option: rpc.MessageOption): boolean { hilog.info(domain, TAG, 'ServiceAbility onRemoteRequest called'); if (code === 1) { let string = data.readString(); hilog.info(domain, TAG, `ServiceAbility string=${string}`); let result = Array.from(string).sort().join(''); hilog.info(domain, TAG, `ServiceAbility result=${result}`); reply.writeString(result); } else { hilog.info(domain, TAG, 'ServiceAbility unknown request code'); } return true; } } //...
application-dev\application-models\create-dataability.md
import featureAbility from '@ohos.ability.featureAbility'; import type common from '@ohos.app.ability.common'; import type Want from '@ohos.app.ability.Want'; import type { AsyncCallback, BusinessError } from '@ohos.base'; import dataAbility from '@ohos.data.dataAbility'; import rdb from '@ohos.data.rdb'; import hilog from '@ohos.hilog'; let TABLE_NAME = 'book'; let STORE_CONFIG: rdb.StoreConfig = { name: 'book.db' }; let SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)'; let rdbStore: rdb.RdbStore | undefined = undefined; const TAG: string = '[Sample_FAModelAbilityDevelop]'; const domain: number = 0xFF00; class DataAbility { onInitialized(want: Want): void { hilog.info(domain, TAG, 'DataAbility onInitialized, abilityInfo:' + want.bundleName); let context: common.BaseContext = { stageMode: featureAbility.getContext().stageMode }; rdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => { hilog.info(domain, TAG, 'DataAbility getRdbStore callback'); store.executeSql(SQL_CREATE_TABLE, []); rdbStore = store; }); } insert(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback<number>): void { hilog.info(domain, TAG, 'DataAbility insert start'); if (rdbStore) { rdbStore.insert(TABLE_NAME, valueBucket, callback); } } batchInsert(uri: string, valueBuckets: Array<rdb.ValuesBucket>, callback: AsyncCallback<number>): void { hilog.info(domain, TAG, 'DataAbility batch insert start'); if (rdbStore) { for (let i = 0; i < valueBuckets.length; i++) { hilog.info(domain, TAG, 'DataAbility batch insert i=' + i); if (i < valueBuckets.length - 1) { rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: BusinessError, num: number) => { hilog.info(domain, TAG, 'DataAbility batch insert ret=' + num); }); } else { rdbStore.insert(TABLE_NAME, valueBuckets[i], callback); } } } } query(uri: string, columns: Array<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<rdb.ResultSet>): void { hilog.info(domain, TAG, 'DataAbility query start'); let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates); if (rdbStore) { rdbStore.query(rdbPredicates, columns, callback); } } update(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void { hilog.info(domain, TAG, 'DataAbility update start'); let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates); if (rdbStore) { rdbStore.update(valueBucket, rdbPredicates, callback); } } delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void { hilog.info(domain, TAG, 'DataAbility delete start'); let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates); if (rdbStore) { rdbStore.delete(rdbPredicates, callback); } } } export default new DataAbility();
application-dev\application-models\create-pageability.md
import featureAbility from '@ohos.ability.featureAbility'; import hilog from '@ohos.hilog'; const TAG: string = 'MainAbility'; const domain: number = 0xFF00; class MainAbility { onCreate() { // Obtain the context and call related APIs. let context = featureAbility.getContext(); context.getBundleName((data, bundleName) => { hilog.info(domain, TAG, 'ability bundleName:' ,bundleName); }); hilog.info(domain, TAG, 'Application onCreate'); } onDestroy() { hilog.info(domain, TAG, 'Application onDestroy'); } onShow(): void { hilog.info(domain, TAG, 'Application onShow'); } onHide(): void { hilog.info(domain, TAG, 'Application onHide'); } onActive(): void { hilog.info(domain, TAG, 'Application onActive'); } onInactive(): void { hilog.info(domain, TAG, 'Application onInactive'); } onNewWant() { hilog.info(domain, TAG, 'Application onNewWant'); } } export default new MainAbility();
application-dev\application-models\create-pageability.md
import featureAbility from '@ohos.ability.featureAbility'; import fs from '@ohos.file.fs'; import promptAction from '@ohos.promptAction'; import hilog from '@ohos.hilog'; const TAG: string = 'PagePageAbilityFirst'; const domain: number = 0xFF00;
application-dev\application-models\create-pageability.md
(async (): Promise<void> => { let dir: string; try { hilog.info(domain, TAG, 'Begin to getOrCreateDistributedDir'); dir = await featureAbility.getContext().getOrCreateDistributedDir(); promptAction.showToast({ message: dir }); hilog.info(domain, TAG, 'distribute dir is ' + dir); let fd: number; let path = dir + '/a.txt'; fd = fs.openSync(path, fs.OpenMode.READ_WRITE).fd; fs.close(fd); } catch (error) { hilog.error(domain, TAG, 'getOrCreateDistributedDir failed with : ' + error); } })()
application-dev\application-models\create-serviceability.md
import { Want } from '@kit.AbilityKit'; import { rpc } from '@kit.IPCKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[Sample_FAModelAbilityDevelop]'; const domain: number = 0xFF00; class FirstServiceAbilityStub extends rpc.RemoteObject { constructor(des: Object) { if (typeof des === 'string') { super(des); } else { return; } } onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence, option: rpc.MessageOption): boolean { hilog.info(domain, TAG, 'ServiceAbility onRemoteRequest called'); if (code === 1) { let string = data.readString(); hilog.info(domain, TAG, `ServiceAbility string=${string}`); let result = Array.from(string).sort().join(''); hilog.info(domain, TAG, `ServiceAbility result=${result}`); reply.writeString(result); } else { hilog.info(domain, TAG, 'ServiceAbility unknown request code'); } return true; } } class ServiceAbility { onStart(): void { hilog.info(domain, TAG, 'ServiceAbility onStart'); } onStop(): void { hilog.info(domain, TAG, 'ServiceAbility onStop'); } onCommand(want: Want, startId: number): void { hilog.info(domain, TAG, 'ServiceAbility onCommand'); } onConnect(want: Want): rpc.RemoteObject { hilog.info(domain, TAG, 'ServiceAbility onDisconnect' + want); return new FirstServiceAbilityStub('test'); } onDisconnect(want: Want): void { hilog.info(domain, TAG, 'ServiceAbility onDisconnect' + want); } } export default new ServiceAbility();
application-dev\application-models\deep-linking-startup.md
// EntryAbility.ets is used as an example. import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { url } from '@kit.ArkTS'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // Obtain the input link information from want. // For example, the input URL is link://www.example.com/programs?action=showall. let uri = want?.uri; if (uri) { // Parse the query parameter from the link. You can perform subsequent processing based on service requirements. let urlObject = url.URL.parseURL(want?.uri); let action = urlObject.params.get('action'); // For example, if action is set to showall, all programs are displayed. if (action === "showall") { // ... } } } }
application-dev\application-models\deep-linking-startup.md
import { common, OpenLinkOptions } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[UIAbilityComponentsOpenLink]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Index { build() { Button('start link', { type: ButtonType.Capsule, stateEffect: true }) .width('87%') .height('5%') .margin({ bottom: '12vp' }) .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let link: string = "link://www.example.com"; let openLinkOptions: OpenLinkOptions = { appLinkingOnly: false }; try { context.openLink(link, openLinkOptions) .then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'open link success.'); }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `open link failed. Code is ${err.code}, message is ${err.message}`); }); } catch (paramError) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to start link. Code is ${paramError.code}, message is ${paramError.message}`); } }) } }
application-dev\application-models\deep-linking-startup.md
import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[UIAbilityComponentsOpenLink]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Index { build() { Button('start ability', { type: ButtonType.Capsule, stateEffect: true }) .width('87%') .height('5%') .margin({ bottom: '12vp' }) .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let want: Want = { uri: "link://www.example.com" }; try { context.startAbility(want).then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'start ability success.'); }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `start ability failed. Code is ${err.code}, message is ${err.message}`); }); } catch (paramError) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to start ability. Code is ${paramError.code}, message is ${paramError.message}`); } }) } }
application-dev\application-models\deep-linking-startup.md
// index.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Web({ src: $rawfile('index.html'), controller: this.controller }) .onLoadIntercept((event) => { const url: string = event.data.getRequestUrl(); if (url === 'link://www.example.com') { (this.getUIContext().getHostContext() as common.UIAbilityContext).openLink(url) .then(() => { console.log('openLink success'); }).catch((err: BusinessError) => { console.error('openLink failed, err:' + JSON.stringify(err)); }); return true; } // If true is returned, the loading is blocked. Otherwise, the loading is allowed. return false; }) } } }
application-dev\application-models\embeddeduiextensionability.md
import { EmbeddedUIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit'; const TAG: string = '[ExampleEmbeddedAbility]'; export default class ExampleEmbeddedAbility extends EmbeddedUIExtensionAbility { onCreate() { console.log(TAG, `onCreate`); } onForeground() { console.log(TAG, `onForeground`); } onBackground() { console.log(TAG, `onBackground`); } onDestroy() { console.log(TAG, `onDestroy`); } onSessionCreate(want: Want, session: UIExtensionContentSession) { console.log(TAG, `onSessionCreate, want: ${JSON.stringify(want)}`); let param: Record<string, UIExtensionContentSession> = { 'session': session }; let storage: LocalStorage = new LocalStorage(param); session.loadContent('pages/extension', storage); } onSessionDestroy(session: UIExtensionContentSession) { console.log(TAG, `onSessionDestroy`); } }
application-dev\application-models\embeddeduiextensionability.md
import { UIExtensionContentSession } from '@kit.AbilityKit'; @Entry() @Component struct Extension { @State message: string = 'EmbeddedUIExtensionAbility Index'; localStorage: LocalStorage | undefined = this.getUIContext().getSharedLocalStorage(); private session: UIExtensionContentSession | undefined = this.localStorage?.get<UIExtensionContentSession>('session'); build() { Column() { Text(this.message) .fontSize(20) .fontWeight(FontWeight.Bold) Button('terminateSelfWithResult').fontSize(20).onClick(() => { this.session?.terminateSelfWithResult({ resultCode: 1, want: { bundleName: 'com.example.embeddeddemo', abilityName: 'ExampleEmbeddedAbility' }}); }) }.width('100%').height('100%') } }
application-dev\application-models\embeddeduiextensionability.md
import { Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State message: string = 'Message: ' private want: Want = { bundleName: 'com.example.embeddeddemo', abilityName: 'EmbeddedUIExtAbility', parameters: { 'ohos.extension.processMode.hostInstance': 'true' } } build() { Row() { Column() { Text(this.message).fontSize(30) EmbeddedComponent(this.want, EmbeddedType.EMBEDDED_UI_EXTENSION) .width('100%') .height('90%') .onTerminated((info: TerminationInfo) => { this.message = 'Termination: code = ' + info.code + ', want = ' + JSON.stringify(info.want); }) .onError((error: BusinessError) => { this.message = 'Error: code = ' + error.code; }) } .width('100%') } .height('100%') } }
application-dev\application-models\file-processing-apps-startup.md
// xxx.ets import { fileUri } from '@kit.CoreFileKit'; import { UIAbility, Want, common, wantConstant } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { window } from '@kit.ArkUI';
application-dev\application-models\file-processing-apps-startup.md
// xxx.ets // Assume that the bundle name is com.example.demo. export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { // Obtain the application sandbox path of the file. let filePath = this.context.filesDir + '/test1.txt'; // Convert the application sandbox path into a URI. let uri = fileUri.getUriFromPath(filePath); // The obtained URI is file://com.example.demo/data/storage/el2/base/files/test.txt. } // ... }
application-dev\application-models\file-processing-apps-startup.md
// xxx.ets export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { // Obtain the application sandbox path of the file. let filePath = this.context.filesDir + '/test.txt'; // Convert the application sandbox path into a URI. let uri = fileUri.getUriFromPath(filePath); // Construct the request data. let want: Want = { action: 'ohos.want.action.viewData', // Action of viewing data. The value is fixed at this value in the file opening scenario. uri: uri, type: 'general.plain-text', // Type of the file to open. // Grant the read and write permissions on the file to the target application. flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION }; } // ... }
application-dev\application-models\file-processing-apps-startup.md
// xxx.ets export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { // Obtain the application sandbox path of the file. let filePath = this.context.filesDir + '/test.txt'; // Convert the application sandbox path into a URI. let uri = fileUri.getUriFromPath(filePath); // Construct the request data. let want: Want = { action: 'ohos.want.action.viewData', // Action of viewing data. The value is fixed at this value in the file opening scenario. uri: uri, type: 'general.plain-text', // Type of the file to open. // Grant the read and write permissions on the file to the target application. flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION }; // Call startAbility. this.context.startAbility(want) .then(() => { console.info('Succeed to invoke startAbility.'); }) .catch((err: BusinessError) => { console.error(`Failed to invoke startAbility, code: ${err.code}, message: ${err.message}`); }); } // ... }
application-dev\application-models\file-processing-apps-startup.md
// xxx.ets import fs from '@ohos.file.fs'; import { Want, AbilityConstant } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { // Obtain the uri field from the want information. let uri = want.uri; if (uri == null || uri == undefined) { console.info('uri is invalid'); return; } try { // Perform operations on the URI of the file as required. For example, open the URI to obtain the file object in read/write mode. let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); console.info('Succeed to open file.'); } catch (err) { let error: BusinessError = err as BusinessError; console.error(`Failed to open file openSync, code: ${error.code}, message: ${error.message}`); } } }
application-dev\application-models\hop-cross-device-migration.md
import { AbilityConstant, UIAbility } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { PromptAction } from '@kit.ArkUI'; const TAG: string = '[MigrationAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class MigrationAbility extends UIAbility { // Prepare data to migrate in onContinue. onContinue(wantParam: Record<string, Object>):AbilityConstant.OnContinueResult { let targetVersion = wantParam.version; let targetDevice = wantParam.targetDevice; hilog.info(DOMAIN_NUMBER, TAG, `onContinue version = ${targetVersion}, targetDevice: ${targetDevice}`); // The application can set the minimum compatible version based on the source version, which can be obtained from the versionCode field in the app.json5 file. This is to prevent incompatibility caused because the target version is too earlier. let versionThreshold: number = -1; // Use the minimum version supported by the application. // Compatibility verification let promptAction: promptAction = uiContext.getPromptAction; if (targetVersion < versionThreshold) { // It is recommended that users be notified of the reason why the migration is rejected if the version compatibility check fails. promptAction.showToast({ message: 'The target application version is too early to continue. Update the application and try again.', duration: 2000 }) // Return MISMATCH when the compatibility check fails. return AbilityConstant.OnContinueResult.MISMATCH; } // Save the data to migrate in the custom field (for example, data) of wantParam. const continueInput = 'Data to migrate'; wantParam['data'] = continueInput; return AbilityConstant.OnContinueResult.AGREE; } }
application-dev\application-models\hop-cross-device-migration.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[MigrationAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class MigrationAbility extends UIAbility { storage : LocalStorage = new LocalStorage(); onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onCreate'); if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { // Restore the saved data from want.parameters. let continueInput = ''; if (want.parameters !== undefined) { continueInput = JSON.stringify(want.parameters.data); hilog.info(DOMAIN_NUMBER, TAG, `continue input ${JSON.stringify(continueInput)}`); } // Trigger page restoration. this.context.restoreWindowStage(this.storage); } } onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(DOMAIN_NUMBER, TAG, 'onNewWant'); if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { // Restore the saved data from want.parameters. let continueInput = ''; if (want.parameters !== undefined) { continueInput = JSON.stringify(want.parameters.data); hilog.info(DOMAIN_NUMBER, TAG, `continue input ${JSON.stringify(continueInput)}`); } // Trigger page restoration. this.context.restoreWindowStage(this.storage); } } }
application-dev\application-models\hop-cross-device-migration.md
// MigrationAbility.ets import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[MigrationAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class MigrationAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // ... this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { hilog.info(DOMAIN_NUMBER, TAG, `setMissionContinueState INACTIVE result: ${JSON.stringify(result)}`); }); // ... } }
application-dev\application-models\hop-cross-device-migration.md
// Page_MigrationAbilityFirst.ets import { AbilityConstant, common } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[MigrationAbility]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_MigrationAbilityFirst { private context = this.getUIContext().getHostContext(); build() { // ... } // ... onPageShow(){ // When the page is displayed, set the migration state to ACTIVE. this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', `setMissionContinueState ACTIVE result: ${JSON.stringify(result)}`); }); } }
application-dev\application-models\hop-cross-device-migration.md
// Page_MigrationAbilityFirst.ets import { AbilityConstant, common } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { PromptAction } from '@kit.ArkUI'; const TAG: string = '[MigrationAbility]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_MigrationAbilityFirst { private context = this.getUIContext().getHostContext(); let promptAction: promptAction = uiContext.getPromptAction; build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { // When the button is clicked, set the migration state to ACTIVE. this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', `setMissionContinueState ACTIVE result: ${JSON.stringify(result)}`); promptAction.showToast({ message: 'Success' }); }); }) } //... } //... } //... } }
application-dev\application-models\hop-cross-device-migration.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class MigrationAbility extends UIAbility { storage : LocalStorage = new LocalStorage(); onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // ... // Trigger page restoration before the synchronous API finishes the execution. this.context.restoreWindowStage(this.storage); } }
application-dev\application-models\hop-cross-device-migration.md
// MigrationAbility.ets import { AbilityConstant, UIAbility, wantConstant } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; const TAG: string = '[MigrationAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class MigrationAbility extends UIAbility { onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult { // ... // Configure not to use the system page stack during restoration. wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; return AbilityConstant.OnContinueResult.AGREE; } onWindowStageRestore(windowStage: window.WindowStage): void { // If the system page stack is not used for restoration, specify the page to be displayed after the migration. windowStage.loadContent('pages/page_migrationability/Page_MigrationAbilityThird', (err, data) => { if (err.code) { hilog.error(DOMAIN_NUMBER, TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } }); } }
application-dev\application-models\hop-cross-device-migration.md
import { AbilityConstant, UIAbility, wantConstant } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[MigrationAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class MigrationAbility extends UIAbility { // ... onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult { hilog.info(DOMAIN_NUMBER, TAG, `onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`); wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; return AbilityConstant.OnContinueResult.AGREE; } }
application-dev\application-models\hop-cross-device-migration.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[MigrationAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class MigrationAbility extends UIAbility { storage : LocalStorage = new LocalStorage(); onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onCreate'); // 1. Quick start is configured. Trigger the lifecycle callback when the application is launched immediately. if (launchParam.launchReason === AbilityConstant.LaunchReason.PREPARE_CONTINUATION) { // If the application data to migrate is large, add a loading screen here (for example, displaying "loading" on the screen). // Handle issues related to custom redirection and timing. // ... } } onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(DOMAIN_NUMBER, TAG, 'onNewWant'); // 1. Quick start is configured. Trigger the lifecycle callback when the application is launched immediately. if (launchParam.launchReason === AbilityConstant.LaunchReason.PREPARE_CONTINUATION) { // If the application data to migrate is large, add a loading screen here (for example, displaying "loading" on the screen). // Handle issues related to custom redirection and timing. // ... } // 2. Trigger the lifecycle callback when the migration data is restored. if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { // Restore the saved data from want.parameters. let continueInput = ''; if (want.parameters !== undefined) { continueInput = JSON.stringify(want.parameters.data); hilog.info(DOMAIN_NUMBER, TAG, `continue input ${JSON.stringify(continueInput)}`); } // Trigger page restoration. this.context.restoreWindowStage(this.storage); } } }
application-dev\application-models\hop-cross-device-migration.md
import { UIAbility } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { UIContext, window } from '@kit.ArkUI'; export default class EntryAbility extends UIAbility { private uiContext: UIContext | undefined = undefined; // ... onWindowStageCreate(windowStage: window.WindowStage): void { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); windowStage.loadContent('pages/Index', (err) => { if (err.code) { hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } this.uiContext = windowStage.getMainWindowSync().getUIContext(); hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.'); }); } onWindowStageRestore(windowStage: window.WindowStage): void { setTimeout(() => { // Throw the asynchronous task execution route to ensure that the task is executed after the home page is loaded. this.uiContext?.getRouter().pushUrl({ url: 'pages/examplePage' }); }, 0); } // ... }
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
18