了解更多请访问:https://harmonyos.51cto.com,官方与华为共建的鸿蒙技术社区。1.前言先说一下我在写这个跨设备文件服务信件管理应用之??前的想法,先看了梁滴滴基于分布式文件服务的文本编辑器,也想做一个文档,比如创建word,excel,pdf文件,然后点击打开WPS软件进行编辑,可惜在网上找不到打开WPS的方法,最后还是放弃了;然后就想到弄个画板,把自己想表达的内容画在画板上,保存为图片,打开图片可以跨设备查看,一开始保存图片,想用截屏方法,但是在文档中找不到Java调用系统的截屏方法,看到了JS,但是需要API7支持,最后放弃了,但是脑子里灵光一闪提醒我,当时我是以前学习,上自习课不用大声说话,很多同学传笔记。写信也很流行,所以我就带着这个想法开始了编码。这里有几个知识点,我以前没有写过,比如如何把文本框里输入的内容写在信纸上,然后保存为图片保存到另外一个设备上。点击图片,可以查看里面的内容,也可以上网搜索,或者查找类似的知识点,今天就可以做出这款跨设备的文件查看应用。先简单说一下这款跨设备的信件管理应用。A手机创建一封邮件信件,生成图片,本地端显示在手机A上,远端显示在手机B上,同时手机A和B都可以打开查看信件内容.这里采用分布式数据库管理,使用列表存储图片名称,方便列表展示。然后点击对应的图片获取图片名称,然后到分发的文件路径获取图片并显示。2.在效果开发工具环境下实现视频:https://www.bilibili.com/video/BV16L4y1i7b1/Mobile+移动环境下的视频:https://www.bilibili.com/video/BV1mL411g72B/3.创建一个这里的工程就好像你安装了最新版的DevEco-Studio开发工具,点击文件->新建->新建工程...弹出创建HarmonyOS工程窗口,这里我选择一个空白的Java模板创建。前面的视频播放例子是用JS写的接口。这个跨设备的邮件管理界面是用Java写的。JS写界面更快,调试也更快。Java模块Layout模块4.主界面开发首先介绍公共类Java代码。有了这些公共类,对于类似功能的应用程序,可以直接复制公共类。可以使用常用文件:DistributedFileUtil分布式文件工具类:packagecom.army.study.util;importcom.army.study.ResourceTable;importohos.agp.render.Canvas;importohos.agp.render.Paint;importohos.agp.render。纹理;importohos.agp.utils.Color;importohos.app.Context;importohos.global.resource.NotExistException;importohos.media.image.ImagePacker;importohos.media.image.ImageSource;importohos.media.image.PixelMap;importohos。media.image.common.Size;importjava.io.*;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;/***分布式文件工具类*/publicclassDistributedFileUtil{//ContextprivatefinalContextmContext;/***构造方法*@paramcontext*/publicDistributedFileUtil(Contextcontext){this.mContext=context;}/***写信*@paramfileName*@paramletterContent*@return*/publicPixelMapwriteLetter(StringfileName,StringletterContent){//获取分发文件路径StringfilePath=mContext.getDistributedDir()+File.separator+fileName+.jpg";Texturetexture=null;try{//从资源文件中获取文具背景图片InputStreaminputStream=mContext.getResourceManager().getResource(ResourceTable.Media_bg);ImageSource.SourceOptionssrcOpts=newImageSource.SourceOptions();srcOpts.formatHint="image/jpeg";ImageSourceimageSource=ImageSource.create(inputStream,srcOpts);//设置图片参数ImageSource.DecodingOptionsdecode=newImageSource.DecodingOptions();decodingOptions.desiredSize=newSize(720,1080);PixelMappixelMap=imageSource.createPixelmap(decodingOptions);//用来保存绘制结果texture=newTexture(pixelMap);Canvascanvas=newCanvas(texture);Paintpaint=newPaint();paint.setTextSize(50);paint.setStrokeWidth(8);paint.setColor(Color.BLACK);//在文具上写内容canvas.drawChars(paint,letterContent.toCharArray(),50,140);//文件输出流FileOutputStreamfos=newFileOutputStream(filePath);ImagePackerimagePacker=ImagePacker.create();ImagePacker.PackingOptionspackingOptions=newImagePacker.PackingOptions();packingOptions.format="image/jpeg";//只支持image/jpegpackingOptions.quality=90;booleanresult=imagePacker.initializePacking(fos,packingOptions);if(result){//这里获取绘制后的pixelMap保存"文件大小:"+dataSize);ToastUtil.getInstance().showToast(mContext,"创建成功!");}}fos.flush();fos.close();}catch(IOException|NotExistExceptione){System.out.println("文件保存错误:"+e.getMessage());e.printStackTrace();}returntexture.getPixelMap();}/***读信*@paramfileName*@paramletterContent*@return*/publicPixelMapreadImage(StringfileName,StringletterContent){//获取分布式文件路径StringfilePath=mContext.getDistributedDir()+File.separator+fileName;//根据分布式文件路径生成文件Filefile=newFile(filePath);if(!file.exists()){//如果文件不存在,调用写信writeLetter(fileName,letterContent);}//图片参数ImageSource.SourceOptionssrcOpts=newImageSource.SourceOptions();srcOpts.formatHint="image/jpeg";//创建图像ourceImageSourceimageSource=ImageSource.create(file,srcOpts);//生成图片PixelMappixelMap=imageSource.createPixelmap(null);returnpixelMap;}/***获取文件列表*@return*/publicListgetFileList(){//获取分发文件列表File[]files=mContext.getDistributedDir().listFiles();ListlistFile=newArrayList<>(Arrays.asList(files));//排序文件顺序listFile.sort((file,newFile)->{if(file.lastModified()>newFile.lastModified()){return-1;}elseif(file.lastModified()==newFile.lastModified()){return0;}else{return1;}});ListlistFileName=newArrayList<>();//获取文件列表文件名(Filef:listFile){if(f.isFile()){Stringname=f.getName();listFileName.add(name);}}returnlistFileName;}}ToastUtil提示信息框:packagecom.army.study.util;importcom.army.study.ResourceTable;importohos.agp.components.Component;importohos.agp.components.LayoutScatter;importohos.agp.components.Text;importohos.agp.window.dialog.ToastDialog;importohos.app.Context;*Toast工具类**/publicclassToastUtil{privateToastDialogtoastDialog;privateToastUtil(){}publicstaticToastUtilgetInstance(){returnToastUtilInstance.INSTANCE;}privatestaticclassToastUtilInstance{privatestaticfinalToastUtilINSTANCE=newToastUtil();}/***显示Toast**@paramcontext*@paramcontent*/publicvoidshowToast(Contextcontext,Stringcontent){if(toastDialog!=null&&toastDialog.isShowing()){toastDialog.cancel();}ComponenttoastLayout=LayoutScatter.getInstance(context).parse(ResourceTable.Layout_layout_toast,null,false);TexttoastText=(文本)toastLayout.findComponentById(ResourceTable.Id_text_msg_toast);toastText.setText(内容);toastDialog=newToastDialog(上下文);toastDialog.setComponent(toastLayout);toastDialog.setTransparent(true);toastDialog.show();}}预览信息内容:/***预览信息内容*/publicclassPreviewLetterDialogextendsCommonDialog{publicPreviewLetterDialog(Contextcontext,PixelMapimgId){super(context);Componentcontainer=LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_previce_letter,null,false);setContentCustomComponent(容器);setSize(MATCH_PARENT,MATCH_CONTENT);setCornerRadius(AttrHelper.vp2px(20,context));Imageimage=(Image)container.findComponentById(ResourceTable.Id_preview);image.setPixelMap(imgId);ButtonbtnCancel=(Button)container.findComponentById(ResourceTable.Id_button_dialog_create_file_cancel);ButtonbtnConfirm=(按钮)容器.findComponentById(ResourceTable.Id_button_dialog_create_file_confirm);btnCancel.setClickedListener(component->{destroy();});btnConfirm.setClickedListener(component->{destroy();});}}写信对象对话框:/***写信对象对话框*/publicclassCreateLetterDialogextendsCommonDialog{privateOnCallBackonCallBack;publicCreateLetterDialog(Contextcontext){super(context);Componentcontainer=LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_write_letter,null,false);setContentCustomComponent(container);Optionaldisplay=DisplayManager.getInstance().getDefaultDisplay(context);intwidth=(int)(display.get().getAttributes().width*0.9);intheight=AttrHelper.vp2px(270,context);setSize(宽度,高度);setCornerRadius(AttrHelper.vp2px(20,context));TextFieldletterContent=(TextField)container.findComponentById(ResourceTable.Id_tf_dialog_create_file_name);ButtonbtnCancel=(Button)container.findComponentById(ResourceTable.Id_button_dialog_create_file_cancel);ButtonbtnComponentConfirm=(ButtonResourceBTableycontainerI).Id_button_dialog_create_file_confirm);btnConfirm.setEnabled(false);btnConfirm.setAlpha(0.5f);letterContent.addTextObserver((text,i,i1,i2)->{if(text.isEmpty()){btnConfirm.setEnabled(false);btnConfirm.setAlpha(0.5f);}else{btnConfirm.setEnabled(true);btnConfirm.setAlpha(1f);}});btnCancel.setClickedListener(组件->{destroy();});btnConfirm.setClickedListener(组件->{if(onCallBack!=null){//设备IDStringdeviceID=KvManagerFactory.getInstance().createKvManager(newKvManagerConfig(context)).getLocalDeviceInfo().getId();//组合文件名,方方便区分是否为当前设备创建的文件Stringname=deviceID+"-"+letterContent.getText();onCallBack.onConfirm(name);}destroy();});}publicvoidsetOnCallBack(OnCallBackonCallBack){this.onCallBack=onCallBack;}publicinterfaceOnCallBack{voidonConfirm(Stringname);}}主界面代码图:讲解到此结束,别忘了config的权限配置。在module.json文件中添加"reqPermissions":[{"name":"ohos.permission.DISTRIBUTED_DATASYNC"},{"name":"ohos.permission.GET_DISTRIBUTED_DEVICE_INFO"},{"name":"ohos.permission.DISTRIBUTED_DEVICE_STATE_CHANGE"},{"name":"ohos.permission.WRITE_MEDIA"},{"name":"ohos.permission.READ_MEDIA"}],更多信息请访问:与华为共建的鸿蒙技术社区https:///harmonyos.51cto.com