当前位置:网站首页>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 :
边栏推荐
- 如何在自有APP内实现小程序实现连麦直播
- Golang error handling
- Qt中的QFile读写文件操作
- ES6 summary "suggestions collection" of array methods find(), findindex()
- Excel之VBA简单宏编程
- 微服务大行其道的今天,Service Mesh是怎样一种存在?
- R language uses the transmute function of dplyr package to calculate the moving window mean value of the specified data column in dataframe data, and uses ggplot2 package to visualize the line graph b
- 数据仓库(四)之ETL开发
- LiveData postValue会“丢”数据
- R语言使用dplyr包的transmute函数计算dataframe数据中的指定数据列的移动窗口均值、使用ggplot2包可视化移动均值与原始数据的折线图
猜你喜欢
Leetcode-141 circular linked list
洞态在某互联⽹⾦融科技企业的最佳落地实践
宏观视角看抖音全生态
Leetcode-83 delete duplicate elements in the sorting linked list
Today, with the popularity of micro services, how does service mesh exist?
LeetCode-21合并两个有序链表
How to use the low code platform of the Internet of things for personal settings?
LiveData postValue会“丢”数据
Facebook聊单,SaleSmartly有妙招!
Lumiprobe非荧光炔烃丨EU(5-乙炔基尿苷)
随机推荐
Popular science: what does it mean to enter the kernel state?
LeetCode-21合并两个有序链表
Reading notes series "modern methods of C language programming" -- Chapter 2
如何运营好技术相关的自媒体?
磁盘的基本知识和基本命令
Three simple methods of ES6 array de duplication
Write it down once Net travel management background CPU Explosion Analysis
js找出数字在数组中下一个相邻的元素
记一次 .NET 差旅管理后台 CPU 爆高分析
2020,最新手机号码手机验证正则表达式,持续更新
Li Kou daily question - Day 32 -1232 Dotted line
12 data dimensioning processing methods
太爱速M源码搭建,巅峰小店APP溢价寄卖源码分享
Leetcode-83 删除排序链表中重复的元素
Regular expression
R language uses the aggregate function of epidisplay package to divide numerical variables into different subsets based on factor variables, and calculate the summary statistics of each subset
如何使用物联网低代码平台进行个人设置?
Weekly recommended short videos: be alert to the confusion between "phenomena" and "problems"
数据库基础:select基本查询语句
Taiaisu M source code construction, peak store app premium consignment source code sharing