当前位置:网站首页>Appgallery connect scenario development practice - image storage and sharing
Appgallery connect scenario development practice - image storage and sharing
2022-07-01 19:00:00 【Huawei Developer Forum】
brief introduction
In the last article Scene development practice in , We use AppGallery Connect( hereinafter referred to as AGC) Certification service of 、 Cloud functions 、 Short message service and other services realize the function of user registration notification . This time , We use AGC Cloud functions provided 、 Cloud storage and App Linking The three services realize the storage of pictures 、 Online editing and sharing , The relevant code has been synchronized to Github.
Implementation Overview
- The user selects the picture to be uploaded on the client , Call cloud storage Android/iOS The upload interface uploads pictures to cloud storage .
- Create a cloud function that handles images , Select cloud storage trigger , Whenever a new picture is uploaded in the cloud storage, the cloud function will be triggered for thumbnail processing .
- Calling cloud storage in cloud function Node.js SDK Download file interface to download pictures to memory , Process pictures in a specific way , And then call cloud storage. Node.js SDK The upload interface in uploads the processed pictures back to cloud storage .
- End side cloud storage Android/iOS SDK After downloading the thumbnail on cloud storage , adopt AppLinking Generate sharing links to share with friends , After friends click the link, they can directly open to the specified page of the application .
Upload pictures from the end side to cloud storage
Please log in AppGallery Connect Official website , And operate in the console :
- Enable Cloud storage services
- Create a new storage instance
- Set cloud storage security policy
- Set cloud storage folder structure
Actions in your app :
1、 Using cloud storage Android SDK Medium getStorageReference Method to create a reference for the cloud address where the uploaded file is stored :
AGCStorageManagement storageManagement = AGCStorageManagement.getInstance();StorageReference reference = storageManagement.getStorageReference("images/demo.jpg");
2、 call SDK The upload interface in uploads local files to the storage instance :
UploadTask task = reference.putFile(new File("path/images/test.jpg"));task.addOnFailureListener(new OnFailureListener(){ @Override public void onFailure(@NonNull Exception exception) { }}).addOnSuccessListener(new OnSuccessListener<UploadTask.UploadResult>(){ @Override public void onSuccess(UploadTask.UploadResult uploadResult) { }});
Cloud storage triggers cloud functions
stay AppGallery Connect Operations in the console :
- Sign in AppGallery Connect, Locate the cloud function and enable it .
- Create a new function and set the function name , Deployment information and other related settings .
- stay “ Code file ” Configuration item , Upload the function deployment package for processing the image size to the cloud function .
- Create cloud storage trigger , Enter the name of the previously created storage instance and select the event name as Complete( After uploading the picture successfully, it starts to trigger the cloud function to cut the picture ).
Cloud function processing picture size
Actions in your app :
1、 Call cloud storage Node.js SDK Specify the instance and bucket to be downloaded, and specify the local address :
const storage = new StorageManagement();const bucket = storage.bucket("photo-7iawi");const remoteFile = bucket.file(fileAddr);localAddr = “\ImageProcess\picture”;
2、 Call the method to download the file :
try { remoteFile.createReadStream() .on('error', err => { result = {"message":"download file error, " + err.message}; callback(result); }) .on('end', () => { result = {"message":"download file success"}; // callback(result); }) .pipe(fs.createWriteStream(localFile)); } catch (error) { result = {"message":"download file error, " + error.message}; callback(result); }
3、 After downloading the file, process the image resolution .
4、 After the image processing is completed, upload the new image back to cloud storage .
const options = { destination: 'thumbnail/' + fileName, onUploadProgress: (event) => { } }; bucket.upload(imageAddr, options) .then(res => { result = {"message":"All Success"}; callback(result); }).catch(err => { result = {"message":"upload failed"}; callback(result); });
App Linking Link sharing
Please log in AppGallery Connect Official website , And operate in the console :
- Enable App Linking service .
- After the service is enabled , On the link prefix tab , Create a unique link prefix in the whole network .
- Configure your application signature SHA256 file , Please refer to Configure signature fingerprint Certificate .
Actions in your app :
1、 Use the cloud storage interface to obtain the download link of the corresponding image .
private String downloadUrl;private void getDownLoadUrl() { AGCStorageManagement storageManagement = AGCStorageManagement.getInstance(); StorageReference reference = storageManagement.getStorageReference("images/demo.jpg"); Task<Uri> task = reference.getDownloadUrl(); task.addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { String downloadUrl = uri.toString(); } }); task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { } }); }
2、 The link and the corresponding picture will be downloaded ID Generate shared Links .
private String shortLink;private static final String DOMAIN_URI_PREFIX = "https:// DomainUriPrefix.drcn.agconnect.link"; private static final String SHARE_DEEP_LINK = "share://photo.share.com"; private void createShareLinking(String UserName, String PhotoID, String ImageUrl) { String newDeep_Link = SHARE_DEEP_LINK + "?PhotoID=" + PhotoID; AppLinking.Builder builder = AppLinking.newBuilder() .setUriPrefix(DOMAIN_URI_PREFIX) .setDeepLink(Uri.parse(ImageUrl)) .setAndroidLinkInfo(AppLinking.AndroidLinkInfo.newBuilder() .setAndroidDeepLink(newDeep_Link) .build()) .setSocialCardInfo(AppLinking.SocialCardInfo.newBuilder() .setTitle("It is a beautiful Photo") .setImageUrl(ImageUrl) .setDescription(UserName + " share a Photo to you") .build()) .setCampaignInfo(AppLinking.CampaignInfo.newBuilder() .setName("UserSharePhoto") .setSource("ShareInApp") .setMedium("MediumExample") .build()); builder.buildShortAppLinking().addOnSuccessListener(shortAppLinking -> { shortLink = shortAppLinking.getShortUrl().toString(); }).addOnFailureListener(e -> { }); }
3、 stay AndroidManifest Middle configuration Intent-Filter, Used to receive App Linking Link and directly pull up the application .
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:host=" DomainUriPrefix.drcn.agconnect.link" android:scheme="http"/> <data android:host=" DomainUriPrefix.drcn.agconnect.link" android:scheme="https"/> </intent-filter></activity>
4、 On the application launch page OnCreate In the method , Receive and process App Linking The method of linking .
AGConnectAppLinking.getInstance().getAppLinking(LoginActivity.this).addOnSuccessListener(resolvedLinkData -> { Log.i(TAG,"StartUp From AppLinking"); if (resolvedLinkData!= null) { String deepLink = resolvedLinkData.getDeepLink().toString(); // your action of StartUp From AppLinking }}).addOnFailureListener(e-> { Log.i(TAG,"Normal StartUp"); // your action of Normal StartUp });
Testing capabilities
You can do the following to test whether pictures or videos can be shared normally :
- Open your app , Take a random picture and store it in your phone .
- View the processing effect after image upload .
- Enter the picture details interface , Click the share link in the upper right corner , See if a link is generated and sent to friends .
- Log in to the app with a friend account , Check and click the link , Test whether the shared picture page can be opened normally .
More reference , please download Demo.
For more details , Please see the :
Huawei official website :
https://developer.huawei.com/consumer/cn/forum/topic/0203726140997690403?fid=0101271690375130218?ha_source=zzh
Reference documents :
Upload pictures using cloud storage :
Use Applinking Share links :
Create cloud functions :
边栏推荐
- Write it down once Net travel management background CPU Explosion Analysis
- 太爱速M源码搭建,巅峰小店APP溢价寄卖源码分享
- After studying 11 kinds of real-time chat software, I found that they all have these functions
- Graduation summary
- Leetcode-21 combines two ordered linked lists
- Lumiprobe biomolecular quantification - qudye Protein Quantification Kit
- R语言epiDisplay包ordinal.or.display函数获取有序logistic回归模型的汇总统计信息(变量对应的优势比及其置信区间、以及假设检验的p值)、write.csv函数保存csv
- 华为云专家详解GaussDB(for MySQL)新特性
- 洞态在某互联⽹⾦融科技企业的最佳落地实践
- How does factor analysis calculate weights?
猜你喜欢
docker 部署mysql8.0
Why do independent website sellers start to do social media marketing? The original customer conversion rate can be improved so much!
Huawei game failed to initialize init with error code 907135000
2. Create your own NFT collections and publish a Web3 application to show them start and run your local environment
透过华为军团看科技之变(六):智慧公路
用GSConv+Slim Neck改进Yolov5,将性能提升到极致!
实现一个Prometheus exporter
Lumiprobe non fluorescent alkyne EU (5-ethynyluridine)
Clean up system cache and free memory under Linux
Privacy sandbox is finally coming
随机推荐
Leetcode203 remove linked list elements
精耕渠道共谋发展 福昕携手伟仕佳杰开展新产品培训大会
Database foundation: select basic query statement
用GSConv+Slim Neck改进Yolov5,将性能提升到极致!
R语言ggplot2可视化:gganimate创建动态柱状图动画(gif)、在动画中沿给定维度逐步显示柱状图、enter_grow函数和enter_fade函数控制运动内插退出(渐变tweening)
Halcon image calibration enables subsequent image processing to become the same as the template image
Livedata postvalue will "lose" data
Cache problems after app release
Evaluation of 6 red, yellow and black list cameras: who is the safest? Who has good picture quality? From now on, let you no longer step on thunder
R语言ggplot2可视化:可视化折线图、使用labs函数为折线图添加自定义的Y轴标签信息(customize y axis label)
Openai video pre training (VPT): action learning based on watching unmarked online videos
Qt中的QFile读写文件操作
实现一个Prometheus exporter
ES6数组去重的三个简单办法
毕业总结
【快应用】text组件里的文字很多,旁边的div样式会被拉伸如何解决
R语言使用epiDisplay包的tableStack函数制作统计汇总表格(基于目标变量分组的描述性统计、假设检验等)、不设置by参数则计算数据框指定数据列范围的基础描述性统计信息
[AGC] how to solve the problem that the local display of event analysis data is inconsistent with that in AGC panel?
用WPF写一款开源方便、快捷的数据库文档查询、生成工具
2020, the regular expression for mobile phone verification of the latest mobile phone number is continuously updated