source
stringlengths
14
113
code
stringlengths
10
21.3k
application-dev\basic-services\account\manage-os-account-credential.md
let challenge: Uint8Array = await userIDM.openSession();
application-dev\basic-services\account\manage-os-account-credential.md
let credentialInfo: osAccount.CredentialInfo = { credType: osAccount.AuthType.PIN, credSubType: osAccount.AuthSubType.PIN_SIX, token: new Uint8Array([0]) };
application-dev\basic-services\account\manage-os-account-credential.md
userIDM.addCredential(credentialInfo, { onResult: (code: number, result: osAccount.RequestResult) => { console.log('addCredential code = ' + code); console.log('addCredential result = ' + result); } });
application-dev\basic-services\account\manage-os-account-credential.md
let challenge: Uint8Array = new Uint8Array([1, 2, 3, 4, 5]); let authType: osAccount.AuthType = osAccount.AuthType.PIN; let authTrustLevel: osAccount.AuthTrustLevel = osAccount.AuthTrustLevel.ATL1;
application-dev\basic-services\account\manage-os-account-credential.md
let userAuth: osAccount.UserAuth = new osAccount.UserAuth(); userAuth.auth(challenge, authType, authTrustLevel, { onResult: (result: number, extraInfo: osAccount.AuthResult) => { console.log('pin auth result = ' + result); console.log('pin auth extraInfo = ' + JSON.stringify(extraInfo)); let authToken = extraInfo.token; } });
application-dev\basic-services\account\manage-os-account-credential.md
let faceCredInfo: osAccount.CredentialInfo = { credType: osAccount.AuthType.FACE, credSubType: osAccount.AuthSubType.FACE_2D, token: new Uint8Array([1, 2, 3, 4, 5]) }
application-dev\basic-services\account\manage-os-account-credential.md
userIDM.addCredential(faceCredInfo, { onResult: (code: number, result: osAccount.RequestResult) => { console.log('add face credential, resultCode: ' + code); console.log('add face credential, request result: ' + result); } });
application-dev\basic-services\account\manage-os-account-credential.md
let fingerprintCredInfo: osAccount.CredentialInfo = { credType: osAccount.AuthType.FINGERPRINT, credSubType: osAccount.AuthSubType.FINGERPRINT_CAPACITIVE, token: new Uint8Array([1, 2, 3, 4, 5]) }
application-dev\basic-services\account\manage-os-account-credential.md
userIDM.addCredential(fingerprintCredInfo, { onResult: (code: number, result: osAccount.RequestResult) => { console.log('add fingerprint credential, resultCode: ' + code); console.log('add fingerprint credential, request result: ' + result); } });
application-dev\basic-services\account\manage-os-account-credential.md
let challenge: Uint8Array = new Uint8Array([1, 2, 3, 4, 5]); let authType: osAccount.AuthType = osAccount.AuthType.FACE; let authTrustLevel: osAccount.AuthTrustLevel = osAccount.AuthTrustLevel.ATL1;
application-dev\basic-services\account\manage-os-account-credential.md
let userAuth: osAccount.UserAuth = new osAccount.UserAuth(); userAuth.auth(challenge, authType, authTrustLevel, { onResult: (result: number, extraInfo: osAccount.AuthResult) => { console.log('face auth result = ' + result); console.log('face auth extraInfo = ' + JSON.stringify(extraInfo)); } });
application-dev\basic-services\account\manage-os-account-credential.md
let credentialInfo: osAccount.CredentialInfo = { credType: osAccount.AuthType.PIN, credSubType: osAccount.AuthSubType.PIN_SIX, token: new Uint8Array([1, 2, 3, 4, 5]) };
application-dev\basic-services\account\manage-os-account-credential.md
userIDM.updateCredential(credentialInfo, { onResult: (result: number, extraInfo: osAccount.RequestResult) => { console.log('updateCredential result = ' + result); console.log('updateCredential extraInfo = ' + extraInfo); } });
application-dev\basic-services\account\manage-os-account-credential.md
let enrolledCredInfoList: osAccount.EnrolledCredInfo[] = await userIDM.getAuthInfo();
application-dev\basic-services\account\manage-os-account-credential.md
let enrolledFingerCredInfoList: osAccount.EnrolledCredInfo[] = await userIDM.getAuthInfo(osAccount.AuthType.FINGERPRINT);
application-dev\basic-services\account\manage-os-account-credential.md
let credentialId: Uint8Array = new Uint8Array([1, 2, 3, 4, 5]); let token: Uint8Array = new Uint8Array([1, 2, 3, 4, 5]) let credInfoList: osAccount.EnrolledCredInfo[] = await userIDM.getAuthInfo(osAccount.AuthType.FINGERPRINT); if (credInfoList.length != 0) { credentialId = credInfoList[0].credentialId; }
application-dev\basic-services\account\manage-os-account-credential.md
userIDM.delCred(credentialId, token, { onResult: (result: number, extraInfo: osAccount.RequestResult) => { console.log('delCred result = ' + result); console.log('delCred extraInfo = ' + JSON.stringify(extraInfo)); } });
application-dev\basic-services\account\manage-os-account-credential.md
pinAuth.unregisterInputer();
application-dev\basic-services\account\manage-os-account-credential.md
userIDM.closeSession();
application-dev\basic-services\account\manage-os-account.md
import { osAccount, BusinessError } from '@kit.BasicServicesKit';
application-dev\basic-services\account\manage-os-account.md
let accountManager = osAccount.getAccountManager();
application-dev\basic-services\account\manage-os-account.md
let name: string = 'Bob'; let type: osAccount.OsAccountType = osAccount.OsAccountType.NORMAL; accountManager.createOsAccount(name, type, (err: BusinessError, osAccountInfo: osAccount.OsAccountInfo)=>{ console.log('createOsAccount err:' + JSON.stringify(err)); console.log('createOsAccount osAccountInfo:' + JSON.stringify(osAccountInfo)); });
application-dev\basic-services\account\manage-os-account.md
accountManager.queryAllCreatedOsAccounts((err: BusinessError, accountArr: osAccount.OsAccountInfo[])=>{ console.log('queryAllCreatedOsAccounts err:' + JSON.stringify(err)); console.log('queryAllCreatedOsAccounts accountArr:' + JSON.stringify(accountArr)); });
application-dev\basic-services\account\manage-os-account.md
let localId: number = 100; accountManager.queryOsAccountById(localId, (err: BusinessError, accountInfo: osAccount.OsAccountInfo)=>{ console.log('queryOsAccountById err:' + JSON.stringify(err)); console.log('queryOsAccountById accountInfo:' + JSON.stringify(accountInfo)); });
application-dev\basic-services\account\manage-os-account.md
let localId: number = 100; let newPhoto: string = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAPCAYAAAA/I0V3AAAAAXNSR0IArs4c6QAAAARnQU1BAA'+ 'Cxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACwSURBVDhPvZLBDYMwDEV/ugsXRjAT0EHCOuFIBwkbdIRewi6unbiAyoGgSn1SFH85+Y'+ 'q/4ljARW62X+LHS8uIzjm4dXUYF+utzBikB52Jo5e5iEPKqpACk7R9NM2RvWm5tIkD2czLCUFNKLD6IjdMHFHDzws285MgGrT0xCtp3WOKHo'+ '+7q0mP0DZW9pNmoEFUzrQjp5cCnaen2kSJXLFD8ghbXyZCMQf/8e8Ns1XVAG/XAgqKzVnJFAAAAABJRU5ErkJggg==' accountManager.setOsAccountProfilePhoto(localId, newPhoto, (err: BusinessError)=>{ console.log('setOsAccountProfilePhoto err:' + JSON.stringify(err)); });
application-dev\basic-services\account\manage-os-account.md
let localId: number = 100; let newName: string = 'Tom'; accountManager.setOsAccountName(localId, newName, (err: BusinessError) => { if (err) { console.error('setOsAccountName failed, error: ' + JSON.stringify(err)); } else { console.log('setOsAccountName successfully'); } });
application-dev\basic-services\account\manage-os-account.md
let localId: number = 101; accountManager.activateOsAccount(localId, (err: BusinessError)=>{ if (err) { console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`); } else { console.log('activateOsAccount successfully'); } });
application-dev\basic-services\account\manage-os-account.md
let localId: number = 101; accountManager.removeOsAccount(localId, (err: BusinessError)=>{ if (err) { console.error('removeOsAccount failed, error: ' + JSON.stringify(err)); } else { console.log('removeOsAccount successfully'); } });
application-dev\basic-services\common-event\common-event-publish.md
import { BusinessError, commonEventManager } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = 'ProcessModel'; const DOMAIN_NUMBER: number = 0xFF00;
application-dev\basic-services\common-event\common-event-publish.md
// Publish the common event. Replace the event field with the actual event name. commonEventManager.publish('event', (err: BusinessError) => { if (err) { hilog.error(DOMAIN_NUMBER, TAG, `Publish failed, code is ${JSON.stringify(err.code)}, message is ${JSON.stringify(err.message)}`); } else { //... hilog.info(DOMAIN_NUMBER, TAG, `Publish success`); } });
application-dev\basic-services\common-event\common-event-publish.md
import { BusinessError, commonEventManager } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = 'ProcessModel'; const DOMAIN_NUMBER: number = 0xFF00;
application-dev\basic-services\common-event\common-event-publish.md
// Attributes of a common event. let options: commonEventManager.CommonEventPublishData = { code: 1, // Result code of the common event. data: 'initial data', // Initial data of the common event. };
application-dev\basic-services\common-event\common-event-publish.md
// Publish the common event. Replace the event field with the actual event name. commonEventManager.publish('event', options, (err: BusinessError) => { if (err) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to publish common event. Code is ${err.code}, message is ${err.message}`); } else { //... hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in publishing common event.`); } });
application-dev\basic-services\common-event\common-event-remove-sticky.md
import { BusinessError, commonEventManager } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = 'ProcessModel'; const DOMAIN_NUMBER: number = 0xFF00;
application-dev\basic-services\common-event\common-event-remove-sticky.md
// Remove the sticky common event. Replace the event field with the actual event name. commonEventManager.removeStickyCommonEvent('event', (err: BusinessError) => { // sticky_event indicates the name of the target sticky common event. if (err) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to remove sticky common event. Code is ${err.code}, message is ${err.message}`); return; } //... hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in removing sticky event.`); });
application-dev\basic-services\common-event\common-event-static-subscription.md
import { commonEventManager, StaticSubscriberExtensionAbility } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = 'StaticSubscriber'; const DOMAIN_NUMBER: number = 0xFF00; export default class StaticSubscriber extends StaticSubscriberExtensionAbility { onReceiveEvent(event: commonEventManager.CommonEventData): void { hilog.info(DOMAIN_NUMBER, TAG, 'onReceiveEvent, event: ' + event.event); //... } }
application-dev\basic-services\common-event\common-event-subscription.md
import { BusinessError, commonEventManager } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = 'ProcessModel'; const DOMAIN_NUMBER: number = 0xFF00;
application-dev\basic-services\common-event\common-event-subscription.md
// Used to save the created subscriber object for subsequent subscription and unsubscription. let subscriber: commonEventManager.CommonEventSubscriber | null = null; //Subscriber information. Replace the event field with the actual event name. let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = { events: ['event'], // Subscribe to the common event screen-off. };
application-dev\basic-services\common-event\common-event-subscription.md
// Callback for subscriber creation. commonEventManager.createSubscriber(subscribeInfo, (err: BusinessError, data: commonEventManager.CommonEventSubscriber) => { if (err) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); return; } hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in creating subscriber.'); subscriber = data; })
application-dev\basic-services\common-event\common-event-subscription.md
// Callback for common event subscription. if (subscriber !== null) { commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => { if (err) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to subscribe common event. Code is ${err.code}, message is ${err.message}`); return; } // ... }) } else { hilog.error(DOMAIN_NUMBER, TAG, `Need create subscriber`); }
application-dev\basic-services\common-event\common-event-unsubscription.md
import { BusinessError, commonEventManager } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = 'ProcessModel'; const DOMAIN_NUMBER: number = 0xFF00;
application-dev\basic-services\common-event\common-event-unsubscription.md
// The subscriber object is created during event subscription. if (subscriber !== null) { commonEventManager.unsubscribe(subscriber, (err: BusinessError) => { if (err) { hilog.error(DOMAIN_NUMBER, TAG, `UnsubscribeCallBack err = ${JSON.stringify(err)}`); } else { hilog.info(DOMAIN_NUMBER, TAG, `Unsubscribe success`); subscriber = null; } }) }
application-dev\basic-services\common-event\itc-with-emitter.md
import { emitter, Callback } from '@kit.BasicServicesKit';
application-dev\basic-services\common-event\itc-with-emitter.md
// Define an event with eventId 1. let event: emitter.InnerEvent = { eventId: 1 }; // Define a callback for an event. let callback: Callback<emitter.EventData> = (eventData: emitter.EventData) => { console.info(`eventData: ${JSON.stringify(eventData)}`); } // Execute the callback after receiving the event whose eventId is 1. emitter.on(innerEvent, callback);
application-dev\basic-services\common-event\itc-with-emitter.md
// Execute the callback after receiving the event whose eventId is 1. // Note that the event is received only once using once(), while the event is received until the subscription is canceled using on(). emitter.once(innerEvent, callback);
application-dev\basic-services\common-event\itc-with-emitter.md
// Define an event with eventId 1 and priority Low. let event: emitter.InnerEvent = { eventId: 1, priority: emitter.EventPriority.LOW }; let callback: Callback<emitter.EventData> = (eventData: emitter.EventData) => { console.info(`eventData: ${JSON.stringify(eventData)}`); } // Subscribes to the event and receive eventData. emitter.once(event, callback); let eventData: emitter.EventData = { data: { content: 'emitter', id: 1, isEmpty: false } }; // Emit the event with eventId 1 and event content eventData. emitter.emit(event, eventData);
application-dev\basic-services\common-event\itc-with-emitter.md
// Unsubscribe from the event with eventId 1. emitter.off(1);
application-dev\basic-services\compress\deflate-and-inflate.md
import { fileIo as fs} from '@kit.CoreFileKit'; import { BusinessError, zlib } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State dataSize: number = 0; build() { Row() { Column() { // Create the data.txt file and write test data. Button('Create a test file data.txt').onClick(() => { let path = this.getUIContext()?.getHostContext()?.filesDir; // Create the data.txt file. let inFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // Write test data. for (let index = 0; index < 100; index++) { fs.writeSync(inFile.fd, index + ': hello world, hello world, hello world, hello world, hello world.\n'); } // Obtain the original size of the test data and save it to dataSize. let stat = fs.statSync(inFile.path); this.dataSize = stat.size; console.info('dataSize: ' + this.dataSize); // Close the file. fs.closeSync(inFile); }) } } .height('100%') .width('100%') } }
application-dev\basic-services\compress\deflate-and-inflate.md
import { fileIo as fs} from '@kit.CoreFileKit'; import { BusinessError, zlib } from '@kit.BasicServicesKit'; @Entry @Component struct Index { build() { Row() { // Example 1: Compress the data.txt file into the data.zip file. Button('compressFile').onClick(() => { let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = path + '/data.txt'; let outFile = path + '/data.zip'; let options: zlib.Options = {}; zlib.compressFile(inFile, outFile, options).then((data: void) => { console.info('compressFile success, data: ' + JSON.stringify(data)); }).catch((errData: BusinessError) => { console.error(`compressFile errCode: ${errData.code}, message: ${errData.message}`); }) }) // Example 2: Decompress the data.zip file to the application sandbox directory. Button('decompressFile').onClick(() => { let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = path + '/data.zip'; let outFile = path; let options: zlib.Options = {}; zlib.decompressFile(inFile, outFile, options).then((data: void) => { console.info('decompressFile success, data: ' + JSON.stringify(data)); }).catch((errData: BusinessError) => { console.error(`decompressFile errCode: ${errData.code}, message: ${errData.message}`); }) }) } .height('100%') .width('100%') } }
application-dev\basic-services\compress\deflate-and-inflate.md
import { fileIo as fs} from '@kit.CoreFileKit'; import { BusinessError, zlib } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State dataSize: number = 0; // Size of the original data. build() { Row() { // Example 1: Read the data.txt file and save it to a buffer. Call the compress API to compress the data in the source buffer to the destination buffer and write the content in the destination buffer to the data.bin file. Button('compress buffer').onClick(() => { let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.bin', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // Read the content of the data.txt file and save the content to the buffer inBuf. let stat = fs.statSync(inFile.path); let inBuf = new ArrayBuffer(stat.size); let readLen = fs.readSync(inFile.fd, inBuf); console.info(`original size: ${stat.size}, read len: ${readLen}`); // Obtain the size of the original data and save it. this.dataSize = stat.size; // Create a compressed object instance. let zip = zlib.createZipSync(); // Obtain the upper limit of a destination buffer. zip.compressBound(stat.size).then((data) => { console.info(`the max dest buf len is ${data}`); // Destination buffer outBuf. let outBuf = new ArrayBuffer(data); // Compress the data in inBuf to outBuf. zip.compress(outBuf, inBuf, readLen).then((zipOutInfo) => { console.info(`compress success, status ${zipOutInfo.status}, destLen ${zipOutInfo.destLen}`); // Write the data in outBuf to the data.bin file. let writeLen = fs.writeSync(outFile.fd, outBuf, { length: zipOutInfo.destLen }); console.info(`write destBuf to data.bin, writeLen ${writeLen}`); // Close the file. fs.closeSync(inFile.fd); fs.closeSync(outFile.fd); }).catch((errData: BusinessError) => { console.error(`errData is errCode:${errData.code} message:${errData.message}`); }) }).catch((errData: BusinessError) => { console.error(`errData is errCode:${errData.code} message:${errData.message}`); }) }) // Example 2: Read the compressed data in the data.bin file and save it to a buffer. Call the uncompress API to decompress the data in the source buffer to the destination buffer and write the content in the destination buffer to the data.txt file. Button('uncompress buffer').onClick(() => { let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.bin', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // Read the compressed data in the data.bin file and save the data to the buffer inBuf. let stat = fs.statSync(inFile.path); let inBuf = new ArrayBuffer(stat.size); let readLen = fs.readSync(inFile.fd, inBuf); console.info(`compressed data size: ${stat.size}, read len: ${readLen}`); // Create a destination buffer. dataSize indicates the original size of the data saved before compression. let outBuf = new ArrayBuffer(this.dataSize); console.info(`the dest buf size is ${this.dataSize}`); // Create a compressed object instance. let zip = zlib.createZipSync(); // Decompress the data in inBuf to outBuf. zip.uncompress(outBuf, inBuf, readLen).then((zipOutInfo) => { console.info(`uncompress success, status ${zipOutInfo.status}, destLen ${zipOutInfo.destLen}`); // Write the data in outBuf to the data.txt file. let writeLen = fs.writeSync(outFile.fd, outBuf, { length: zipOutInfo.destLen }); console.info(`write destBuf to data.txt, writeLen ${writeLen}`); // Close the file. fs.closeSync(inFile.fd); fs.closeSync(outFile.fd); }).catch((errData: BusinessError) => { console.error(`errData is errCode:${errData.code} message:${errData.message}`); }) }) } .height('100%') .width('100%') } }
application-dev\basic-services\compress\deflate-and-inflate.md
import { fileIo as fs} from '@kit.CoreFileKit'; import { BusinessError, zlib } from '@kit.BasicServicesKit'; @Entry @Component struct Index { build() { Row() { // Example 1: Continuously read data from a file for compression. Button('deflateFile').onClick(() => { let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.bin', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); deflateFile(inFile, outFile).then(() => { console.info('deflateFile success'); fs.closeSync(inFile.fd); fs.closeSync(outFile.fd); }) }) // Example 2: Continuously read compressed data from the file for decompression. Button('inflateFile').onClick(() => { let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.bin', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); inflateFile(inFile, outFile).then(() => { console.info('deflateFile success'); fs.closeSync(inFile.fd); fs.closeSync(outFile.fd); }) }) } .height('100%') .width('100%') } } // Continuously read data from a file, compress the data, and write the data to another file. async function deflateFile(src: fs.File, dest: fs.File) { let flush = zlib.CompressFlushMode.NO_FLUSH; let strm: zlib.ZStream = {}; // Initialize a compression stream. const BUFLEN = 4096; let inBuf = new ArrayBuffer(BUFLEN); // Initialize an input buffer. let outBuf = new ArrayBuffer(BUFLEN); // Initialize an output buffer. // Create a compressed object instance. let zip = zlib.createZipSync(); // Initialize the stream status. let initStatus = zip.deflateInit(strm, zlib.CompressLevel.COMPRESS_LEVEL_BEST_SPEED); console.info('deflateInit ret: ' + (await initStatus).valueOf()); do { // Read data from a file to a buffer. let readLen = fs.readSync(src.fd, inBuf); console.info("readSync readLen: " + readLen); flush = readLen == 0 ? zlib.CompressFlushMode.FINISH : zlib.CompressFlushMode.NO_FLUSH; // Set the input buffer. strm.availableIn = readLen; strm.nextIn = inBuf; do { // Set the output buffer. strm.availableOut = BUFLEN; strm.nextOut = outBuf; try { // Compress the data in the input buffer to the output buffer. let deflateStatus = zip.deflate(strm, flush); console.info('deflate ret: ' + (await deflateStatus).valueOf()); // Update the stream status. let innerStrm = zip.getZStream(); strm.availableIn = (await innerStrm).availableIn; strm.nextIn = (await innerStrm).nextIn; strm.availableOut = (await innerStrm).availableOut; strm.nextOut = (await innerStrm).nextOut; strm.totalIn = (await innerStrm).totalIn; strm.totalOut = (await innerStrm).totalOut; if (strm.availableOut != undefined) { // Write the compressed data to the output file. let have = BUFLEN - strm.availableOut; let writeLen = fs.writeSync(dest.fd, outBuf, { length: have }); console.info(`writeSync writeLen: ${writeLen}`); } } catch (err) { console.error('deflate err: ' + JSON.stringify(err)); } } while (strm.availableOut == 0); // Compress the remaining data in the input buffer cyclically until all data is compressed. } while (flush != zlib.CompressFlushMode.FINISH); // Read data from the file cyclically until all data is read. // Release resources. zip.deflateEnd(strm); } // Continuously read compressed data from a file, decompress the data, and write the data to another file. async function inflateFile(src: fs.File, dest: fs.File) { let status: zlib.ReturnStatus = zlib.ReturnStatus.OK; let strm: zlib.ZStream = {}; // Initialize a compression stream. const BUFLEN = 4096; let inBuf = new ArrayBuffer(BUFLEN); // Initialize an input buffer. let outBuf = new ArrayBuffer(BUFLEN); // Initialize an output buffer. // Create a compressed object instance. let zip = zlib.createZipSync(); // Initialize the stream status. let initStatus = zip.inflateInit(strm); console.info('inflateInit ret: ' + (await initStatus).valueOf()); do { // Read the compressed data from the file to the buffer. let readLen = fs.readSync(src.fd, inBuf); console.info("readSync readLen: " + readLen); if (readLen == 0) { break; } // Set the input buffer. strm.availableIn = readLen; strm.nextIn = inBuf; do { // Set the output buffer. strm.availableOut = BUFLEN; strm.nextOut = outBuf; try { // Decompress the data in the input buffer to the output buffer. let inflateStatus = zip.inflate(strm, zlib.CompressFlushMode.NO_FLUSH); console.info('inflate ret: ' + (await inflateStatus).valueOf()); // Update the stream status. let innerStrm = zip.getZStream(); strm.availableIn = (await innerStrm).availableIn; strm.nextIn = (await innerStrm).nextIn; strm.availableOut = (await innerStrm).availableOut; strm.nextOut = (await innerStrm).nextOut; strm.totalIn = (await innerStrm).totalIn; strm.totalOut = (await innerStrm).totalOut; if (strm.availableOut != undefined) { // Write the decompressed data to the output file. let have = BUFLEN - strm.availableOut; let writeLen = fs.writeSync(dest.fd, outBuf, { length: have }); console.info(`writeSync writeLen: ${writeLen}`); } } catch (err) { console.error('inflate err: ' + JSON.stringify(err)); } } while (strm.availableOut == 0) // Decompress the remaining data in the input buffer cyclically until all data is decompressed. } while (status != zlib.ReturnStatus.STREAM_END.valueOf()) // Read data from the file cyclically until all data is read. // Release resources. zip.inflateEnd(strm); }
application-dev\basic-services\compress\deflate-and-inflate.md
import { fileIo as fs} from '@kit.CoreFileKit'; import { BusinessError, zlib } from '@kit.BasicServicesKit'; @Entry @Component struct Index { build() { Row() { // Example 1: Continuously read data from a file for compression. Button('deflateGzipFile').onClick(() => { let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.gz', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); deflateGzipFile(inFile, outFile).then(() => { console.info('deflateGzipFile success'); fs.closeSync(inFile.fd); fs.closeSync(outFile.fd); }) }) // Example 2: Continuously read compressed data from the file for decompression. Button('inflateGzipFile').onClick(() => { let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.gz', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); inflateGzipFile(inFile, outFile).then(() => { console.info('deflateGzipFile success'); fs.closeSync(inFile.fd); fs.closeSync(outFile.fd); }) }) } .height('100%') .width('100%') } } // Continuously read data from a file, compress the data, and write the data to another file. async function deflateGzipFile(src: fs.File, dest: fs.File) { let flush = zlib.CompressFlushMode.NO_FLUSH; let strm: zlib.ZStream = {}; // Initialize a compression stream. const BUFLEN = 4096; let inBuf = new ArrayBuffer(BUFLEN); // Initialize an input buffer. let outBuf = new ArrayBuffer(BUFLEN); // Initialize an output buffer. // Create a compressed object instance. let zip = zlib.createZipSync(); // Initialize the stream status. If windowBits is greater than 15, the .gzip format is used. let windowBits = 15 + 16; let initStatus = zip.deflateInit2(strm, zlib.CompressLevel.COMPRESS_LEVEL_BEST_SPEED, zlib.CompressMethod.DEFLATED, windowBits, zlib.MemLevel.MEM_LEVEL_DEFAULT, zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY); console.info('deflateInit2 ret: ' + (await initStatus).valueOf()); do { // Read data from a file to a buffer. let readLen = fs.readSync(src.fd, inBuf); console.info("readSync readLen: " + readLen); flush = readLen == 0 ? zlib.CompressFlushMode.FINISH : zlib.CompressFlushMode.NO_FLUSH; // Set the input buffer. strm.availableIn = readLen; strm.nextIn = inBuf; do { // Set the output buffer. strm.availableOut = BUFLEN; strm.nextOut = outBuf; try { // Compress the data in the input buffer to the output buffer. let deflateStatus = zip.deflate(strm, flush); console.info('deflate ret: ' + (await deflateStatus).valueOf()); // Update the stream status. let innerStrm = zip.getZStream(); strm.availableIn = (await innerStrm).availableIn; strm.nextIn = (await innerStrm).nextIn; strm.availableOut = (await innerStrm).availableOut; strm.nextOut = (await innerStrm).nextOut; strm.totalIn = (await innerStrm).totalIn; strm.totalOut = (await innerStrm).totalOut; if (strm.availableOut != undefined) { // Write the compressed data to the output file. let have = BUFLEN - strm.availableOut; let writeLen = fs.writeSync(dest.fd, outBuf, { length: have }); console.info(`writeSync writeLen: ${writeLen}`); } } catch (err) { console.error('deflate err: ' + JSON.stringify(err)); } } while (strm.availableOut == 0); // Compress the remaining data in the input buffer cyclically until all data is compressed. } while (flush != zlib.CompressFlushMode.FINISH); // Read data from the file cyclically until all data is read. // Release resources. zip.deflateEnd(strm); } // Continuously read compressed data from a file, decompress the data, and write the data to another file. async function inflateGzipFile(src: fs.File, dest: fs.File) { let status: zlib.ReturnStatus = zlib.ReturnStatus.OK; let strm: zlib.ZStream = {}; // Initialize a compression stream. const BUFLEN = 4096; let inBuf = new ArrayBuffer(BUFLEN); // Initialize an input buffer. let outBuf = new ArrayBuffer(BUFLEN); // Initialize an output buffer. // Create a compressed object instance. let zip = zlib.createZipSync(); // Initialize the stream status. If windowBits is greater than 15, the .gzip format is used. let windowBits = 15 + 16; let initStatus = zip.inflateInit2(strm, windowBits); console.info('inflateInit2 ret: ' + (await initStatus).valueOf()); do { // Read the compressed data from the file to the buffer. let readLen = fs.readSync(src.fd, inBuf); console.info("readSync readLen: " + readLen); if (readLen == 0) { break; } // Set the input buffer. strm.availableIn = readLen; strm.nextIn = inBuf; do { // Set the output buffer. strm.availableOut = BUFLEN; strm.nextOut = outBuf; try { // Decompress the data in the input buffer to the output buffer. let inflateStatus = zip.inflate(strm, zlib.CompressFlushMode.NO_FLUSH); console.info('inflate ret: ' + (await inflateStatus).valueOf()); // Update the stream status. let innerStrm = zip.getZStream(); strm.availableIn = (await innerStrm).availableIn; strm.nextIn = (await innerStrm).nextIn; strm.availableOut = (await innerStrm).availableOut; strm.nextOut = (await innerStrm).nextOut; strm.totalIn = (await innerStrm).totalIn; strm.totalOut = (await innerStrm).totalOut; if (strm.availableOut != undefined) { // Write the decompressed data to the output file. let have = BUFLEN - strm.availableOut; let writeLen = fs.writeSync(dest.fd, outBuf, { length: have }); console.info(`writeSync writeLen: ${writeLen}`); } } catch (err) { console.error('inflate err: ' + JSON.stringify(err)); } } while (strm.availableOut == 0) // Decompress the remaining data in the input buffer cyclically until all data is decompressed. } while (status != zlib.ReturnStatus.STREAM_END.valueOf()) // Read data from the file cyclically until all data is read. // Release resources. zip.inflateEnd(strm); }
application-dev\basic-services\pasteboard\pasteboard-time-lapse-copy-and-paste.md
\ import {unifiedDataChannel, uniformTypeDescriptor} from '@kit.ArkData'; import {BusinessError, pasteboard} from '@kit.BasicServicesKit'
application-dev\basic-services\pasteboard\pasteboard-time-lapse-copy-and-paste.md
let plainTextData = new unifiedDataChannel.UnifiedData(); let GetDelayPlainText = ((dataType:string) => { let plainText = new unifiedDataChannel.PlainText(); plainText.details = { Key: 'delayPlaintext', Value: 'delayPlaintext', }; plainText.textContent = 'delayTextContent'; plainText.abstract = 'delayTextContent'; plainTextData.addRecord(plainText); return plainTextData; });
application-dev\basic-services\pasteboard\pasteboard-time-lapse-copy-and-paste.md
let SetDelayPlainText = (() => { plainTextData.properties.shareOptions = unifiedDataChannel.ShareOptions.CROSS_APP; // For cross-application use, set this parameter to CROSS_APP. For intra-application use, set this parameter to IN_APP. plainTextData.properties.getDelayData = GetDelayPlainText; pasteboard.getSystemPasteboard().setUnifiedData(plainTextData).then(()=>{ // The data is successfully saved, which is a normal case. }).catch((error: BusinessError) => { // Error case }); })
application-dev\basic-services\pasteboard\pasteboard-time-lapse-copy-and-paste.md
let GetPlainTextUnifiedData = (() => { pasteboard.getSystemPasteboard().getUnifiedData().then((data) => { let outputData = data; let records = outputData.getRecords(); if (records[0].getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { let record = records[0] as unifiedDataChannel.PlainText; console.log('GetPlainText success, type:' + records[0].getType + ', details:' + JSON.stringify(record.details) + ', textContent:' + record.textContent + ', abstract:' + record.abstract); } else { console.log('Get Plain Text Data No Success, Type is: ' + records[0].getType()); } }).catch((error: BusinessError) => { // Error case }) })
application-dev\basic-services\pasteboard\use_pasteboard_to_copy_and_paste.md
import {unifiedDataChannel, uniformTypeDescriptor} from '@kit.ArkData'; import {BusinessError, pasteboard} from '@kit.BasicServicesKit'; // Construct a piece of PlainText data and write the function for obtaining the delay data. let plainTextData = new unifiedDataChannel.UnifiedData(); let GetDelayPlainText = ((dataType:string) => { let plainText = new unifiedDataChannel.PlainText(); plainText.details = { Key: 'delayPlaintext', Value: 'delayPlaintext', }; plainText.textContent = 'delayTextContent'; plainText.abstract = 'delayTextContent'; plainTextData.addRecord(plainText); return plainTextData; }); // Save a piece of PlainText data to the system pasteboard. let SetDelayPlainText = (() => { plainTextData.properties.shareOptions = unifiedDataChannel.ShareOptions.CROSS_APP; // For cross-application use, set this parameter to CROSS_APP. For intra-application use, set this parameter to IN_APP. plainTextData.properties.getDelayData = GetDelayPlainText; pasteboard.getSystemPasteboard().setUnifiedData(plainTextData).then(()=>{ // The data is successfully saved, which is a normal case. }).catch((error: BusinessError) => { // Error case }); }) // Read the text data from the system pasteboard. let GetPlainTextUnifiedData = (() => { pasteboard.getSystemPasteboard().getUnifiedData().then((data) => { let outputData = data; let records = outputData.getRecords(); if (records[0].getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { let record = records[0] as unifiedDataChannel.PlainText; console.log('GetPlainText success, type:' + records[0].getType + ', details:' + JSON.stringify(record.details) + ', textContent:' + record.textContent + ', abstract:' + record.abstract); } else { console.log('Get Plain Text Data No Success, Type is: ' + records[0].getType()); } }).catch((error: BusinessError) => { // Error case }) })
application-dev\basic-services\pasteboard\use_pasteboard_to_copy_and_paste.md
import {BusinessError, pasteboard} from '@kit.BasicServicesKit'; // Obtain the system pasteboard object. let text = "test"; // Create a pasteboard content object of the plain text type. let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text); // Write data to the system pasteboard. let systemPasteboard = pasteboard.getSystemPasteboard(); await systemPasteboard.setData(pasteData); // Read data from the system pasteboard. systemPasteboard.getData().then((data) => { let outputData = data; // Obtain the number of records from the pasteboard. let recordCount = outputData.getRecordCount(); // Obtain the corresponding record information from the pasteboard data. for (let i = 0; i < recordCount; i++) { let record = outputData.getRecord(i).toPlainText(); console.log('Get data success, record:' + record); } }).catch((error: BusinessError) => { // Error case })
application-dev\basic-services\request\app-file-upload-download.md
// Approach 1: Use request.uploadFile. // pages/xxx.ets import { common } from '@kit.AbilityKit'; import fs from '@ohos.file.fs'; import { BusinessError, request } from '@kit.BasicServicesKit'; @Entry @Component struct Index { build() { Row() { Column() { Button("Upload").onClick(() => { // Obtain the application file path. // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let cacheDir = context.cacheDir; // Create an application file locally. let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); fs.writeSync(file.fd, 'upload file test'); fs.closeSync(file); // Configure the upload task. let files: Array<request.File> = [ // "internal://cache" in uri corresponds to the cacheDir directory. { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } ] let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }]; let uploadConfig: request.UploadConfig = { url: 'https://xxx', header: { 'key1':'value1', 'key2':'value2' }, method: 'POST', files: files, data: data } // Upload the created application file to the network server. try { request.uploadFile(context, uploadConfig) .then((uploadTask: request.UploadTask) => { uploadTask.on('complete', (taskStates: Array<request.TaskState>) => { for (let i = 0; i < taskStates.length; i++) { console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`); } }); }) .catch((err: BusinessError) => { console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); }) } catch (error) { let err: BusinessError = error as BusinessError; console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); } }) } } } }
application-dev\basic-services\request\app-file-upload-download.md
// Approach 2: Use request.agent. // pages/xxx.ets import { common } from '@kit.AbilityKit'; import fs from '@ohos.file.fs'; import { BusinessError, request } from '@kit.BasicServicesKit'; @Entry @Component struct Index { build() { Row() { Column() { Button("Upload").onClick(() => { // Obtain the application file path. // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let cacheDir = context.cacheDir; // Create an application file locally. let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); fs.writeSync(file.fd, 'upload file test'); fs.closeSync(file); let attachments: Array<request.agent.FormItem> = [{ name: "test", value: [ { filename: "test.txt", path: "./test.txt", }, ] }]; let config: request.agent.Config = { action: request.agent.Action.UPLOAD, url: 'http://xxx', mode: request.agent.Mode.FOREGROUND, overwrite: true, method: "POST", headers: { 'key1':'value1', 'key2':'value2' }, data: attachments, saveas: "./" }; request.agent.create(context, config).then((task: request.agent.Task) => { task.start((err: BusinessError) => { if (err) { console.error(`Failed to start the upload task, Code: ${err.code} message: ${err.message}`); return; } }); task.on('progress', async(progress) => { console.warn(`/Request upload status ${progress.state}, uploaded ${progress.processed}`); }) task.on('completed', async() => { console.warn(`/Request upload completed`); // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. request.agent.remove(task.tid); }) }).catch((err: BusinessError) => { console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); }); }) } } } }
application-dev\basic-services\request\app-file-upload-download.md
// Approach 1: Use request.downloadFile. // pages/xxx.ets // Download the network resource file to the local application file directory, and read data from the file. import { common } from '@kit.AbilityKit'; import fs from '@ohos.file.fs'; import { BusinessError, request } from '@kit.BasicServicesKit'; import { buffer } from '@kit.ArkTS'; @Entry @Component struct Index { build() { Row() { Column() { Button("Download").onClick(() => { // Obtain the application file path. // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let filesDir = context.filesDir; try { request.downloadFile(context, { url: 'https://xxxx/xxxx.txt', filePath: filesDir + '/xxxx.txt' }).then((downloadTask: request.DownloadTask) => { downloadTask.on('complete', () => { console.info('download complete'); let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); let arrayBuffer = new ArrayBuffer(1024); let readLen = fs.readSync(file.fd, arrayBuffer); let buf = buffer.from(arrayBuffer, 0, readLen); console.info(`The content of file: ${buf.toString()}`); fs.closeSync(file); }) }).catch((err: BusinessError) => { console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`); }); } catch (error) { let err: BusinessError = error as BusinessError; console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`); } }) } } } }
application-dev\basic-services\request\app-file-upload-download.md
// Approach 2: Use request.agent. // pages/xxx.ets // Download the network resource file to the local application file directory, and read data from the file. import { common } from '@kit.AbilityKit'; import fs from '@ohos.file.fs'; import { BusinessError, request } from '@kit.BasicServicesKit'; import { buffer } from '@kit.ArkTS'; @Entry @Component struct Index { build() { Row() { Column() { Button("Download").onClick(() => { // Obtain the application file path. // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let filesDir = context.filesDir; let config: request.agent.Config = { action: request.agent.Action.DOWNLOAD, url: 'https://xxxx/test.txt', saveas: 'xxxx.txt', gauge: true, overwrite: true, network: request.agent.Network.WIFI, }; request.agent.create(context, config).then((task: request.agent.Task) => { task.start((err: BusinessError) => { if (err) { console.error(`Failed to start the download task, Code: ${err.code} message: ${err.message}`); return; } }); task.on('progress', async (progress) => { console.warn(`/Request download status ${progress.state}, downloaded ${progress.processed}`); }) task.on('completed', async () => { console.warn(`/Request download completed`); let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); let arrayBuffer = new ArrayBuffer(1024); let readLen = fs.readSync(file.fd, arrayBuffer); let buf = buffer.from(arrayBuffer, 0, readLen); console.info(`The content of file: ${buf.toString()}`); fs.closeSync(file); // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. request.agent.remove(task.tid); }) }).catch((err: BusinessError) => { console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); }); }) } } } }
application-dev\basic-services\request\app-file-upload-download.md
import { BusinessError, request } from '@kit.BasicServicesKit'; import { picker } from '@kit.CoreFileKit'; import { common } from '@kit.AbilityKit'; @Entry @Component struct Index { build() { Row() { Column() { Button("Download Document").width("50%").margin({ top: 20 }).height(40).onClick(async () => { // Create a documentSaveOptions instance. const documentSaveOptions = new picker.DocumentSaveOptions(); // (Optional) Name of the file to save. The default value is empty. documentSaveOptions.newFileNames = ["xxxx.txt"]; // (Optional) Type of the document to save. The value is in ['Description|File name extensions'] format. To save all files, use 'All files (*.*)|.*'. If there are multiple file name extensions (a maximum of 100 extensions can be filtered), the first one is used by default. If this parameter is not specified, no extension is filtered by default. documentSaveOptions.fileSuffixChoices = ['Document|.txt', '.pdf']; let uri: string = ''; // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. let context = this.getUIContext().getHostContext() as common.UIAbilityContext; const documentViewPicker = new picker.DocumentViewPicker(context); await documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => { uri = documentSaveResult[0]; console.info('DocumentViewPicker.save to file succeed and uri is:' + uri); }).catch((err: BusinessError) => { console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) if (uri != '') { let config: request.agent.Config = { action: request.agent.Action.DOWNLOAD, url: 'https://xxxx/xxxx.txt', // The saveas field specifies the URI of the file saved by DocumentViewPicker. saveas: uri, gauge: true, // The overwrite field must be set to true. overwrite: true, network: request.agent.Network.WIFI, // The mode field must be set to request.agent.Mode.FOREGROUND. mode: request.agent.Mode.FOREGROUND, }; try { request.agent.create(context, config).then((task: request.agent.Task) => { task.start((err: BusinessError) => { if (err) { console.error(`Failed to start the download task, Code: ${err.code} message: ${err.message}`); return; } }); task.on('progress', async (progress) => { console.warn(`Request download status ${progress.state}, downloaded ${progress.processed}`); }) task.on('completed', async (progress) => { console.warn('Request download completed, ' + JSON.stringify(progress)); // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. request.agent.remove(task.tid); }) }).catch((err: BusinessError) => { console.error(`Failed to operate a download task, Code: ${err.code}, message: ${err.message}`); }); } catch (err) { console.error(`Failed to create a download task, err: ${err}`); } } }) } } } }
application-dev\basic-services\request\app-file-upload-download.md
import { BusinessError, request } from '@kit.BasicServicesKit'; import { picker } from '@kit.CoreFileKit'; import { common } from '@kit.AbilityKit'; @Entry @Component struct Index { build() { Row() { Column() { Button("Download Audio").width("50%").margin({ top: 20 }).height(40).onClick(async () => { // Create a documentSaveOptions instance. const audioSaveOptions = new picker.AudioSaveOptions(); // (Optional) Name of the file to save. The default value is empty. audioSaveOptions.newFileNames = ['xxxx.mp3']; let uri: string = ''; // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. let context = this.getUIContext().getHostContext() as common.UIAbilityContext; const audioViewPicker = new picker.AudioViewPicker(context); await audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array<string>) => { uri = audioSelectResult[0]; console.info('AudioViewPicker.save to file succeed and uri is:' + uri); }).catch((err: BusinessError) => { console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) if (uri != '') { let config: request.agent.Config = { action: request.agent.Action.DOWNLOAD, url: 'https://xxxx/xxxx.mp3', // The saveas field specifies the URI of the file saved by AudioViewPicker. saveas: uri, gauge: true, // The overwrite field must be set to true. overwrite: true, network: request.agent.Network.WIFI, // The mode field must be set to request.agent.Mode.FOREGROUND. mode: request.agent.Mode.FOREGROUND, }; try { request.agent.create(context, config).then((task: request.agent.Task) => { task.start((err: BusinessError) => { if (err) { console.error(`Failed to start the download task, Code: ${err.code} message: ${err.message}`); return; } }); task.on('progress', async (progress) => { console.warn(`Request download status ${progress.state}, downloaded ${progress.processed}`); }) task.on('completed', async (progress) => { console.warn('Request download completed, ' + JSON.stringify(progress)); // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. request.agent.remove(task.tid); }) }).catch((err: BusinessError) => { console.error(`Failed to operate a download task, Code: ${err.code}, message: ${err.message}`); }); } catch (err) { console.error(`Failed to create a download task, err: ${err}`); } } }) } } } }
application-dev\basic-services\request\app-file-upload-download.md
import { BusinessError, request } from '@kit.BasicServicesKit'; import { photoAccessHelper } from '@kit.MediaLibraryKit'; import { bundleManager } from '@kit.AbilityKit'; import { abilityAccessCtrl, Context, PermissionRequestResult, common } from '@kit.AbilityKit'; @Entry @Component struct Index { build() { Row() { Column() { Button("Download Image").width("50%").margin({ top: 20 }).height(40).onClick(async () => { let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA; // Obtain accessTokenID of the application. let tokenID = -1; try { await bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { console.info(`/Request getBundleInfoForSelf successfully. Data: ${JSON.stringify(data)}`); tokenID = data.appInfo.accessTokenId; }).catch((err: BusinessError) => { console.error(`GetBundleInfoForSelf failed. Cause: ${err.message}`); }); } catch (err) { let message = (err as BusinessError).message; console.error('GetBundleInfoForSelf failed: %{public}s', message); } let context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); let grant = true; // Check whether the application has the required permission. This API uses a promise to return the result. await atManager.checkAccessToken(tokenID, 'ohos.permission.WRITE_IMAGEVIDEO') .then((data: abilityAccessCtrl.GrantStatus) => { console.log(`/Request checkAccessToken success, data->${JSON.stringify(data)}`); if (data != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { grant = false; } }) .catch((err: BusinessError) => { console.error(`GheckAccessToken fail, err->${JSON.stringify(err)}`); }); if (!grant) { // Display a dialog box for the user to grant the required permission. This API uses an asynchronous callback to return the result. await atManager.requestPermissionsFromUser(context, ['ohos.permission.WRITE_IMAGEVIDEO']) .then((data: PermissionRequestResult) => { console.info('/Request grant:' + JSON.stringify(data)); console.info('/Request grant permissions:' + data.permissions); console.info('/Request grant authResults:' + data.authResults); console.info('/Request grant dialogShownResults:' + data.dialogShownResults); }).catch((err: BusinessError) => { console.error('Grant error:' + JSON.stringify(err)); }); } try { let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; let extension: string = 'jpg'; let options: photoAccessHelper.CreateOptions = { title: 'xxxx' } // Obtain a PhotoAccessHelper instance, which can be used for accessing and modifying media files in an album. let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); // Create an image or video asset with the specified file type, file name extension, and options. This API uses a promise to return the result. let uri: string = await phAccessHelper.createAsset(photoType, extension, options); console.info('/Request createAsset uri' + uri); console.info('/Request createAsset successfully'); let config: request.agent.Config = { action: request.agent.Action.DOWNLOAD, url: 'https://xxxx/xxxx.jpg', // The saveas field specifies the URI of the file saved by PhotoAccessHelper. saveas: uri, gauge: true, // The overwrite field must be set to true. overwrite: true, network: request.agent.Network.WIFI, // The mode field must be set to request.agent.Mode.FOREGROUND. mode: request.agent.Mode.FOREGROUND, }; request.agent.create(context, config).then((task: request.agent.Task) => { task.start((err: BusinessError) => { if (err) { console.error(`Failed to start the download task, Code: ${err.code} message: ${err.message}`); return; } }); task.on('progress', async (progress) => { console.warn(`Request download status ${progress.state}, downloaded ${progress.processed}`); }) task.on('completed', async (progress) => { console.warn('Request download completed, ' + JSON.stringify(progress)); // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. request.agent.remove(task.tid); }) }).catch((err: BusinessError) => { console.error(`Failed to operate a download task, Code: ${err.code}, message: ${err.message}`); }); } catch (err) { console.error(`Failed to create a download task, err: ${err}`); } }) } } } }
application-dev\basic-services\request\app-file-upload-download.md
{ "network-security-config": { "base-config": { "cleartextTrafficPermitted": true, "trust-anchors": [ { "certificates": "/etc/security/certificates" } ] }, "domain-config": [ { "cleartextTrafficPermitted": true, "domains": [ { "include-subdomains": true, "name": "*.example.com" } ], } ] } }
application-dev\basic-services\usb\usb-guidelines.md
// Import the USB API package. import { usbManager } from '@kit.BasicServicesKit'; // Obtain the USB device list. let deviceList : Array<usbManager.USBDevice> = usbManager.getDevices(); /* Example deviceList structure: [ { name: "1-1", serial: "", manufacturerName: "", productName: "", version: "", vendorId: 7531, productId: 2, clazz: 9, subClass: 0, protocol: 1, devAddress: 1, busNum: 1, configs: [ { id: 1, attributes: 224, isRemoteWakeup: true, isSelfPowered: true, maxPower: 0, name: "1-1", interfaces: [ { id: 0, protocol: 0, clazz: 9, subClass: 0, alternateSetting: 0, name: "1-1", endpoints: [ { address: 129, attributes: 3, interval: 12, maxPacketSize: 4, direction: 128, number: 1, type: 3, interfaceId: 0, } ] } ] } ] } ] */
application-dev\basic-services\usb\usb-guidelines.md
import { usbManager } from '@kit.BasicServicesKit'; import { BusinessError } from '@kit.BasicServicesKit'; let deviceName : string = deviceList[0].name; // Request the permissions to operate a specified device. usbManager.requestRight(deviceName).then((hasRight : boolean) => { console.info(`usb device request right result: ${hasRight}`); }).catch((error : BusinessError)=> { console.error(`usb device request right failed : ${error}`); });
application-dev\basic-services\usb\usb-guidelines.md
// Open the device, and obtain the USB device pipe for data transfer. let pipe : usbManager.USBDevicePipe = usbManager.connectDevice(deviceList[0]); let interface1 : usbManager.USBInterface = deviceList[0].configs[0].interfaces[0]; /* Claim the corresponding interface from **deviceList**. interface1 must be one present in the device configuration. */ usbManager.claimInterface(pipe, interface1, true);
application-dev\basic-services\usb\usb-guidelines.md
import { usbManager } from '@kit.BasicServicesKit'; import { BusinessError } from '@kit.BasicServicesKit'; /* Read data. Select the corresponding RX endpoint from deviceList for data transfer. (endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array. */ let inEndpoint : usbManager.USBEndpoint = interface1.endpoints[2]; let outEndpoint : usbManager.USBEndpoint = interface1.endpoints[1]; let dataUint8Array : Uint8Array = new Uint8Array(1024); usbManager.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then((dataLength : number) => { if (dataLength >= 0) { console.info(`usb readData result Length : ${dataLength}`); } else { console.error(`usb readData failed`); } }).catch((error : BusinessError) => { console.error(`usb readData error : ${error}`); }); // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0) usbManager.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then((dataLength : number) => { if (dataLength >= 0) { console.info(`usb writeData result write length : ${dataLength}`); } else { console.error("usb writeData failed"); } }).catch((error : BusinessError) => { console.error(`usb writeData error : ${error}`); });
application-dev\basic-services\usb\usb-guidelines.md
import { usbManager } from '@kit.BasicServicesKit'; import { BusinessError } from '@kit.BasicServicesKit'; /* Construct control transfer parameters. */ let param: usbManager.USBDeviceRequestParams = { bmRequestType: 0x80, // 0x80 indicates a standard request for data transfer from the device to the host. bRequest: 0x06, // 0x06 indicates a request for the descriptor. wValue:0x01 << 8 | 0, // The value is of two bytes. The high byte indicates the descriptor type. Here, 0x01 indicates the device descriptor. The low byte indicates the descriptor index. The value is set to 0 because it is not involved for the device descriptor. wIndex: 0, // Descriptor index. The value can be 0. wLength: 18, // Descriptor length. The value 18 indicates that a maximum of 1024 characters are supported. data: new Uint8Array(18) }; usbManager.usbControlTransfer(pipe, param).then((ret: number) => { console.info(`usbControlTransfer = ${ret}`); })
application-dev\basic-services\usb\usb-guidelines.md
usbManager.releaseInterface(pipe, interface1); usbManager.closePipe(pipe);
application-dev\basic-services\usb\usbManager\usbHost\bulkTransfer.md
// Import the usbManager module. import { usbManager } from '@kit.BasicServicesKit'; import { BusinessError } from '@kit.BasicServicesKit';
application-dev\basic-services\usb\usbManager\usbHost\bulkTransfer.md
// Obtain the USB device list. let deviceList : Array<usbManager.USBDevice> = usbManager.getDevices(); /* Example deviceList structure: [ { name: "1-1", serial: "", manufacturerName: "", productName: "", version: "", vendorId: 7531, productId: 2, clazz: 9, subClass: 0, protocol: 1, devAddress: 1, busNum: 1, configs: [ { id: 1, attributes: 224, isRemoteWakeup: true, isSelfPowered: true, maxPower: 0, name: "1-1", interfaces: [ { id: 0, protocol: 0, clazz: 9, subClass: 0, alternateSetting: 0, name: "1-1", endpoints: [ { address: 129, attributes: 3, interval: 12, maxPacketSize: 4, direction: 128, number: 1, type: 3, interfaceId: 0, } ] } ] } ] } ] */
application-dev\basic-services\usb\usbManager\usbHost\bulkTransfer.md
let deviceName : string = deviceList[0].name; // Request the permissions to operate a specified device. usbManager.requestRight(deviceName).then((hasRight : boolean) => { console.info(`usb device request right result: ${hasRight}`); }).catch((error : BusinessError)=> { console.error(`usb device request right failed : ${error}`); });
application-dev\basic-services\usb\usbManager\usbHost\bulkTransfer.md
// Open the device, and obtain the USB device pipe for data transfer. let pipe : usbManager.USBDevicePipe = usbManager.connectDevice(deviceList[0]); let interface1 : usbManager.USBInterface = deviceList[0].configs[0].interfaces[0]; /* Claim the corresponding interface from deviceList. interface1 must be one present in the device configuration. */ usbManager.claimInterface(pipe, interface1, true);
application-dev\basic-services\usb\usbManager\usbHost\bulkTransfer.md
/* Read data. Select the corresponding RX endpoint from deviceList for data transfer. (endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array. */ let inEndpoint : usbManager.USBEndpoint = interface1.endpoints[2]; let outEndpoint : usbManager.USBEndpoint = interface1.endpoints[1]; let dataUint8Array : Uint8Array = new Uint8Array(1024); usbManager.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then((dataLength : number) => { if (dataLength >= 0) { console.info(`usb readData result Length : ${dataLength}`); } else { console.error("usb readData failed"); } }).catch((error : BusinessError) => { console.error(`usb readData error : ${error}`); }); // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0) usbManager.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then((dataLength : number) => { if (dataLength >= 0) { console.info(`usb writeData result write length : ${dataLength}`); } else { console.error("usb writeData failed"); } }).catch((error : BusinessError) => { console.error(`usb writeData error : ${error}`); });
application-dev\basic-services\usb\usbManager\usbHost\bulkTransfer.md
usbManager.releaseInterface(pipe, interface1); usbManager.closePipe(pipe);
application-dev\basic-services\usb\usbManager\usbHost\controlTransfer.md
// Import the usbManager module. import { usbManager } from '@kit.BasicServicesKit'; import { BusinessError } from '@kit.BasicServicesKit';
application-dev\basic-services\usb\usbManager\usbHost\controlTransfer.md
// Obtain the USB device list. let deviceList : Array<usbManager.USBDevice> = usbManager.getDevices(); /* Example deviceList structure: [ { name: "1-1", serial: "", manufacturerName: "", productName: "", version: "", vendorId: 7531, productId: 2, clazz: 9, subClass: 0, protocol: 1, devAddress: 1, busNum: 1, configs: [ { id: 1, attributes: 224, isRemoteWakeup: true, isSelfPowered: true, maxPower: 0, name: "1-1", interfaces: [ { id: 0, protocol: 0, clazz: 9, subClass: 0, alternateSetting: 0, name: "1-1", endpoints: [ { address: 129, attributes: 3, interval: 12, maxPacketSize: 4, direction: 128, number: 1, type: 3, interfaceId: 0, } ] } ] } ] } ] */
application-dev\basic-services\usb\usbManager\usbHost\controlTransfer.md
let deviceName : string = deviceList[0].name; // Request the permissions to operate a specified device. usbManager.requestRight(deviceName).then((hasRight : boolean) => { console.info("usb device request right result: " + hasRight); }).catch((error : BusinessError)=> { console.error(`usb device request right failed : ${error}`); });
application-dev\basic-services\usb\usbManager\usbHost\controlTransfer.md
// Open the device, and obtain the USB device pipe for data transfer. let pipe : usbManager.USBDevicePipe = usbManager.connectDevice(deviceList[0]); let interface1 : usbManager.USBInterface = deviceList[0].configs[0].interfaces[0]; /* Claim the corresponding interface from deviceList. interface1 must be one present in the device configuration. */ usbManager.claimInterface(pipe, interface1, true);
application-dev\basic-services\usb\usbManager\usbHost\controlTransfer.md
/* Construct control transfer parameters. */ let param: usbManager.USBDeviceRequestParams = { bmRequestType: 0x80, // 0x80 indicates a standard request for data transfer from the device to the host. bRequest: 0x06, // 0x06 indicates a request for the descriptor. wValue:0x01 << 8 | 0, // The value is of two bytes. The high byte indicates the descriptor type. Here, 0x01 indicates the device descriptor. The low byte indicates the descriptor index. The value is set to 0 because it is not involved for the device descriptor. wIndex: 0, // Descriptor index. The value can be 0. wLength: 18, // Descriptor length. The value 18 indicates the length of a device descriptor. A maximum of 1024 characters are supported. data: new Uint8Array(18) }; usbManager.usbControlTransfer(pipe, param).then((ret: number) => { console.info(`usbControlTransfer = ${ret}`); })
application-dev\basic-services\usb\usbManager\usbHost\controlTransfer.md
usbManager.releaseInterface(pipe, interface1); usbManager.closePipe(pipe);
application-dev\basic-services\usb\usbManager\usbHost\deviceManager.md
// Import the usbManager module. import { usbManager } from '@kit.BasicServicesKit'; import { BusinessError } from '@kit.BasicServicesKit';
application-dev\basic-services\usb\usbManager\usbHost\deviceManager.md
// Obtain the USB device list. let deviceList : Array<usbManager.USBDevice> = usbManager.getDevices(); /* Example deviceList structure: [ { name: "1-1", serial: "", manufacturerName: "", productName: "", version: "", vendorId: 7531, productId: 2, clazz: 9, subClass: 0, protocol: 1, devAddress: 1, busNum: 1, configs: [ { id: 1, attributes: 224, isRemoteWakeup: true, isSelfPowered: true, maxPower: 0, name: "1-1", interfaces: [ { id: 0, protocol: 0, clazz: 9, subClass: 0, alternateSetting: 0, name: "1-1", endpoints: [ { address: 129, attributes: 3, interval: 12, maxPacketSize: 4, direction: 128, number: 1, type: 3, interfaceId: 0, } ] } ] } ] } ] */
application-dev\basic-services\usb\usbManager\usbHost\deviceManager.md
let deviceName : string = deviceList[0].name; // Request the permissions to operate a specified device. usbManager.requestRight(deviceName).then((hasRight : boolean) => { console.info("usb device request right result: " + hasRight); }).catch((error : BusinessError)=> { console.error(`usb device request right failed : ${error}`); });
application-dev\basic-services\usb\usbManager\usbHost\deviceManager.md
// Open the device, and obtain the USB device pipe for data transfer. let pipe : usbManager.USBDevicePipe = usbManager.connectDevice(deviceList[0]); let interface1 : usbManager.USBInterface = deviceList[0].configs[0].interfaces[0]; /* Claim the corresponding interface from **deviceList**. interface1 must be one present in the device configuration. */ usbManager.claimInterface(pipe, interface1, true);
application-dev\basic-services\usb\usbManager\usbHost\deviceManager.md
usbManager.releaseInterface(pipe, interface1); usbManager.closePipe(pipe);
application-dev\basic-services\usb\usbManager\usbHost\interruptTransfer.md
// Import the usbManager module. import { usbManager } from '@kit.BasicServicesKit';
application-dev\basic-services\usb\usbManager\usbHost\interruptTransfer.md
// Obtain the list of USB devices connected to the host. let usbDevices: Array<usbManager.USBDevice> = usbManager.getDevices(); console.info(`usbDevices: ${usbDevices}`); if(usbDevices.length === 0) { console.error('usbDevices is empty'); return; }
application-dev\basic-services\usb\usbManager\usbHost\interruptTransfer.md
// Check whether the first USB device in the list has the access permission. let usbDevice: usbManager.USBDevice = usbDevices[0]; if(!usbManager.hasRight(usbDevice.name)) { await usbManager.requestRight(usbDevice.name).then(result => { if(!result) { // If the USB device does not have the access permission and is not granted by the user, the device exits. console.error('The user does not have permission to perform this operation'); return; } }); }
application-dev\basic-services\usb\usbManager\usbHost\interruptTransfer.md
let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(usbDevice); let usbConfigs: usbManager.USBConfiguration[] = usbDevice.configs; let usbInterfaces: usbManager.USBInterface[] = []; let usbInterface: usbManager.USBInterface | undefined = undefined let usbEndpoints: usbManager.USBEndpoint[] = []; let usbEndprint: usbManager.USBEndpoint | undefined = undefined for (let i = 0; i < usbConfigs.length; i++) { usbInterfaces = usbConfigs[i].interfaces; for (let i = 0; i < usbInterfaces.length; i++) { usbEndpoints = usbInterfaces[i].endpoints; usbEndprint = usbEndpoints.find((value) => { return value.direction === 128 && value.type === usbManager.UsbEndpointTransferType.TRANSFER_TYPE_INTERRUPT; }) if (usbEndprint !== undefined) { usbInterface = usbInterfaces[i]; break; } } } if (usbEndprint === undefined) { console.error(`get usbEndprint error`) return; }
application-dev\basic-services\usb\usbManager\usbHost\interruptTransfer.md
// Register a communication interface. If the registration is successful, 0 is returned; otherwise, other error codes are returned. let claimInterfaceResult: number = usbManager.claimInterface(devicePipe, usbInterface, true); if (claimInterfaceResult !== 0) { console.error(`claimInterface error = ${claimInterfaceResult}`) return; }
application-dev\basic-services\usb\usbManager\usbHost\interruptTransfer.md
try { // The communication interface is successfully registered and performs data transfer. let transferParams: usbManager.UsbDataTransferParams = { devPipe: devicePipe, flags: usbManager.UsbTransferFlags.USB_TRANSFER_SHORT_NOT_OK, endpoint: usbEndprint.address, type: usbManager.UsbEndpointTransferType.TRANSFER_TYPE_INTERRUPT, timeout: 2000, length: 10, callback: () => {}, userData: new Uint8Array(10), buffer: new Uint8Array(10), isoPacketCount: 2, }; transferParams.callback = (err: Error, callBackData: usbManager.SubmitTransferCallback) => { console.info(`callBackData = ${callBackData}`); console.info(`transfer success, result = ${transferParams.buffer}`); } usbManager.usbSubmitTransfer(transferParams); console.info('USB transfer request submitted.'); } catch (error) { console.error(`USB transfer failed: ${error}`); }
application-dev\basic-services\usb\usbManager\usbHost\interruptTransfer.md
usbManager.usbCancelTransfer(transferParams); usbManager.releaseInterface(devicePipe, usbInterface); usbManager.closePipe(devicePipe);
application-dev\basic-services\usb\usbManager\usbHost\isochronousTransfer.md
// Import the usbManager module. import { usbManager } from '@kit.BasicServicesKit';
application-dev\basic-services\usb\usbManager\usbHost\isochronousTransfer.md
// Obtain the list of USB devices connected to the host. let usbDevices: Array<usbManager.USBDevice> = usbManager.getDevices(); console.info(`usbDevices: ${usbDevices}`); if(usbDevices.length === 0) { console.error('usbDevices is empty'); return; }
application-dev\basic-services\usb\usbManager\usbHost\isochronousTransfer.md
// Check whether the first USB device in the list has the access permission. let usbDevice: usbManager.USBDevice = usbDevices[0]; if(!usbManager.hasRight(usbDevice.name)) { await usbManager.requestRight(usbDevice.name).then(result => { if(!result) { // If the USB device does not have the access permission and is not granted by the user, the device exits. console.error('The user does not have permission to perform this operation'); return; } }); }
application-dev\basic-services\usb\usbManager\usbHost\isochronousTransfer.md
let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(usbDevice); let usbConfigs: usbManager.USBConfiguration[] = usbDevice.configs; let usbInterfaces: usbManager.USBInterface[] = []; let usbInterface: usbManager.USBInterface | undefined = undefined let usbEndpoints: usbManager.USBEndpoint[] = []; let usbEndprint: usbManager.USBEndpoint | undefined = undefined for (let i = 0; i < usbConfigs.length; i++) { usbInterfaces = usbConfigs[i].interfaces; for (let i = 0; i < usbInterfaces.length; i++) { usbEndpoints = usbInterfaces[i].endpoints; usbEndprint = usbEndpoints.find((value) => { // direction indicates the request direction. The value 0 indicates the written data, and the value 128 indicates the read data. return value.direction === 128 && value.type === usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS; }) if (usbEndprint !== undefined) { usbInterface = usbInterfaces[i]; break; } } } if (usbEndprint === undefined) { console.error(`get usbEndprint error`) return; }