自由流转--实例(二)
1、使用组件迁移数据
@Entry
@Component
struct Index {private arr: number[] = [0,1,2,3,4,5,6,7,8,9,10]build() {Column() {// 部分组件支持分布式迁移List({space: 20}) {ForEach(this.arr, (item: number) => {...},(item: number) => (item.toString()))}// 给需要迁移的组件配置restoreId,不同组件不同的值.restoreId(1)}}
}
2、页面栈迁移
onContinue(wantParam: Record<string, Object | undefined>): AbilityConstant.OnContinueResult {...return AbilityConstant.OnContinueResult.AGREE // 同意迁移
}onCreate(want:Want, launchParam: AbilityConstant.LaunchParam): void {this.checkPermissions()if (launchParam.launchReason === AbilityConstant.LaunchParam.CONTINUATION) {this.context.restoreWindowStage(new LocalStorage));}
}
3、少量状态数据迁移
// 源端:实现源端回调
onContinue(wantParam: {[key:string]: any}) {let sessionId: string = AppStore.get('sessionId') as string;...wantParam['sessionId'] = AppStore.get<string>('sessionId')
}// 对端:恢复数据
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {...if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {AppStorage.setOrCreate<string>('sessionId', want.parameters?.sessionId)this.context.restoreWindowStorage(new LocalStorage())}
}
4、内存数据迁移
创建分布式数据对象
private localObject: distributedDataObject.DataObject | undefined = undefined
...
onWindowStageCreate(windowStage: window.windowStage) {...if(!this.localObject) {let mailInfo: MailInfo = new MailInfo(undefined,undefined,undefined,undefined)this.localObject = distributedDataObject.create(this.context, mailInfo)}...
}
向分布式数据对象写
onContinue(wantParam: Record<string, Object | undefined>): AbilityConstant.OnContinueResult {try {let sessionId: string = AppStorage.get('sessionId') as stringif (!sessionId) {sessionId = distributedDataObject.getSessionId()AppStorage.setOrCreate('sessionId',sessionId)}if (this.loacalObject) {this.localObject.setSessionId(sessionId)this.localObject['recipient'] = AppStorage.get('recipient')this.localObject['sender'] = AppStorage.get('sender')this.localObject['subject'] = AppStorage.get('subject')this.localObject['emailContent'] = AppStorage.get('emailContent')this.localObject.save(wantParam.targetDevice as string)wantParam.siatributedSessionId = sessionId}}
}
从分布式数据对象读
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {if (!this.loacalObject) {let mailInfo: MailInfo = new MailInfo(undefined,undefined,undefined,undefined)this.localObject = distributedDataObject.create(this.context, mailInfo)this.localObject.on('change', this.changeCall)}if (sessionId && this.localObject) {this.localObject.setSessionId(sessionId)AppStorage.setOnCreat('recipient',this.localObject['recipient'])AppStorage.setOnCreat('sender',this.localObject['sender'])AppStorage.setOnCreat('subject',this.localObject['subject'])AppStorage.setOnCreate('emailContent',this.localObject['emailContent'])}this.context.restoreWindowStage(new LocalStorage())}
}
5、使用分布式文件传输数据
@Entry
@Component
struct MailHomePage {aboutToAppear() {if ((this.isContinuation === CommonConstants.CAN_CONTINUATION) && (this.appendix.length >= 1)) {this.readFile();}}build() {// ...}/*** Reading file from distributed file systems.*/readFile(): void {this.appendix.forEach((item: AppendixBean) => {let filePath: string = this.distributedPath + item.fileName;let savePath: string = getContext().filesDir + '/' + item.fileName;try {while (fileIo.accessSync(filePath)) {let saveFile = fileIo.openSync(savePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE);let buf: ArrayBuffer = new ArrayBuffer(CommonConstants.FILE_BUFFER_SIZE);let readSize = 0;let readLen = fileIo.readSync(file.fd, buf, { offset: readSize });while (readLen > 0) {readSize += readLen;fileIo.writeSync(saveFile.fd, buf);readLen = fileIo.readSync(file.fd, buf, { offset: readSize });}fileIo.closeSync(file);fileIo.closeSync(saveFile);}} catch (error) {let err: BusinessError = error as BusinessError;Logger.error(`DocumentViewPicker failed with err: ${JSON.stringify(err)}`);}});}/*** Add appendix from file manager.** @param fileType*/documentSelect(fileType: number): void {try {let DocumentSelectOptions = new picker.DocumentSelectOptions();let documentPicker = new picker.DocumentViewPicker();documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult: Array<string>) => {for (let documentSelectResultElement of DocumentSelectResult) {let buf = new ArrayBuffer(CommonConstants.FILE_BUFFER_SIZE);let readSize = 0;let file = fileIo.openSync(documentSelectResultElement, fileIo.OpenMode.READ_ONLY);let readLen = fileIo.readSync(file.fd, buf, { offset: readSize });// File name is not supported chinese name.let fileName = file.name;if (!fileName.endsWith(imageIndex[fileType].fileType) ||new RegExp("\[\\u4E00-\\u9FA5]|[\\uFE30-\\uFFA0]", "gi").test(fileName)) {promptAction.showToast({message: $r('app.string.alert_message_chinese')})return;}let destination = fileIo.openSync(getContext().filesDir + '/' + fileName, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);let destinationDistribute = fileIo.openSync(getContext().distributedFilesDir + '/' + fileName, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);while (readLen > 0) {readSize += readLen;fileIo.writeSync(destination.fd, buf);fileIo.writeSync(destinationDistribute.fd, buf);console.info(destinationDistribute.path);readLen = fileIo.readSync(file.fd, buf, { offset: readSize });}fileIo.closeSync(file);fileIo.closeSync(destination);fileIo.closeSync(destinationDistribute);this.appendix.push({ iconIndex: fileType, fileName: fileName });}Logger.info(`DocumentViewPicker.select successfully, DocumentSelectResult uri: ${JSON.stringify(DocumentSelectResult)}`);}).catch((err: BusinessError) => {Logger.error(`DocumentViewPicker.select failed with err: ${JSON.stringify(err)}`);});} catch (error) {let err: BusinessError = error as BusinessError;Logger.error(`DocumentViewPicker failed with err: ${JSON.stringify(err)}`);}}
}