当前位置:网站首页>The Chinese Valentine's Day event is romantically launched, don't let the Internet slow down and miss the dark time
The Chinese Valentine's Day event is romantically launched, don't let the Internet slow down and miss the dark time
2022-08-03 23:07:00 【HMS Core】
Valentine's Day is here,各种AppAll busy with new ones,Catch the festive hot spots of internet products,Combine the category of the application for event marketing.比如购物类AppThere will be a big promotion on festivals;旅游类AppVarious promotions will be launched;Short videos and photosAppThere will be a variety of holiday-limited special effects、Exclusive stickers, etc.
尤其是游戏类App,Has strong social attributes,Version updates are generally carried out at festival hotspots,New skins and new scenes are launched,涉及到的内容很多,Sometimes the resources of the version update package are too large,Causes a long wait time for users to update,Affect operation promotion and user download experience.Only access is required at this timeHMS Core Network Kit,It can greatly improve the resource download rate.
HMS Core Network KitIs a network basic service suite,聚合远场网络通信优秀实践,辅以RESTful、文件上传/Download and other scene-based interfaces,Simple and easy to use for you、低时延、高吞吐和高安全的端云传输通道.In addition to boosting file uploads/Download speed and success rate,还可以在URLImprove network access speed in network access scenarios,In a weak network environment, the invalid network waiting time can be reduced,And support network smooth migration.

从图中可以看出,集成Network KitThe download speed improved after approx40%.
HMS Core Network Kit首先在QUIC The self-developed large file congestion control algorithm is superimposed on the protocol,Through efficient concurrent data flow,Effectively improve throughput under weak network;其次,Smart sharding sets different sharding thresholds and the number of shards for different machine environments,Increase the download speed as much as possible;It also supports multi-task concurrent execution and management,Resume the task from a breakpoint,Improve the download success rate.Applies to upgrades with newer versions、补丁升级、Relevant resources such as new scene maps are loaded、活动图片、video download, etc.
开发步骤
在进行开发之前,您需要完成必要的开发准备工作,详情可见Network开发指导文档.
SDKThe integrated sample code is as follows:
dependencies { // 使用Network Kitthe network request function implementation 'com.huawei.hms:network-embedded: 6.0.0.300' // 使用Network Kit的文件上传/下载功能 implementation 'com.huawei.hms:filemanager: 6.0.0.300'}因为Network Kit使用了Java 8的新特性,如:Lambda表达式、static interface methods, etc.所以Network Kitboth need to beGradle添加Java 8environment compilation constraints.
在“compileOptions”Add the following compilation configuration to the .
android{ compileOptions{ sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }}示例代码
文件上传
The file upload function can be realized by the following operations.The detailed development process and code implementation can be found herecodelab(文件上传/下载集成)和示例代码.
- When the adaptation version is Android6.0(API Level 23)及以上时,You need to dynamically apply for read and write mobile phone storage permissions(Only one successful application is required per application).
if (Build.VERSION.SDK_INT >= 23) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000); requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1001); }}- Initialize the global upload management classUploadManager.
UploadManager upManager = (UploadManager) new UploadManager .Builder("uploadManager") .build(context);- Construct the request body object.Let's upload filesfile1和file2为例.
Map<String, String> httpHeader = new HashMap<>();httpHeader.put("header1", "value1");Map<String, String> httpParams = new HashMap<>();httpParams.put("param1", "value1");// Replace it with the destination address you need to upload.String normalUrl = "https://path/upload";// Replace with the address of the file you want to upload.String filePath1 = context.getString(R.string.filepath1);// Replace with the address of the file you want to upload.String filePath2 = context.getString(R.string.filepath2);// 构造POST请求对象.try{ BodyRequest request = UploadManager.newPostRequestBuilder() .url(normalUrl) .fileParams("file1", new FileEntity(Uri.fromFile(new File(filePath1)))) .fileParams("file2", new FileEntity(Uri.fromFile(new File(filePath2)))) .params(httpParams) .headers(httpHeader) .build();}catch(Exception exception){ Log.e(TAG,"exception:" + exception.getMessage());}- 创建FileUploadCallback请求回调类.
FileUploadCallback callback = new FileUploadCallback() { @Override public BodyRequest onStart(BodyRequest request) { // This method is called when the file upload starts. Log.i(TAG, "onStart:" + request); return request; } @Override public void onProgress(BodyRequest request, Progress progress) { // Callback to this method when the file upload progress changes. Log.i(TAG, "onProgress:" + progress); } @Override public void onSuccess(Response<BodyRequest, String, Closeable> response) { // This method is called back when the file is uploaded successfully. Log.i(TAG, "onSuccess:" + response.getContent()); } @Override public void onException(BodyRequest request, NetworkException exception, Response<BodyRequest, String, Closeable> response) { // A network exception occurred during the file upload process,Or call this method when the request is canceled. if (exception instanceof InterruptedException) { String errorMsg = "onException for canceled"; Log.w(TAG, errorMsg); } else { String errorMsg = "onException for:" + request.getId() + " " + Log.getStackTraceString(exception); Log.e(TAG, errorMsg); } }};- Send a request to upload the specified file,And get whether the upload started successfully.
当Result的getCodeThe return value and static variable obtained by the methodResult.SUCCESSIf they are consistent, the file upload task starts successfully.
Result result = upManager.start(request, callback);// Whether the upload task was started successfully,可以通过Result的getCode()Whether the return value obtained by the method is the same as the static variableResult.SUCCESS一致来判断.if (result.getCode() != Result.SUCCESS) { Log.e(TAG, result.getMessage());}- File upload status callback.
When the file upload status changes,步骤4创建的FileUploadCallbackThe different callback methods of the object will be called.
• When the file upload starts,onStart方法会被调用.
• When the file upload progress changes,onProgress方法会被调用,And can be called by parsingProgress对象,获取上传进度.
• When an exception occurs in the file upload task,onException方法会被调用.
- 验证上传结果.
After the file is uploaded successfully, it will call back to the step4创建的FileUploadCallbackThe request callback objectonSuccess方法.
文件下载
The file download function can be realized by the following operations.Please refer to the detailed development process and code implementationcodelab(文件上传/下载集成)和示例代码.
- When the adaptation version is Android6.0(API Level 23)及以上时,You need to dynamically apply for read and write mobile phone storage permissions(Only one successful application is required per application).
if (Build.VERSION.SDK_INT >= 23) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000); requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1001); }}- Initialize the global download management classDownloadManager.
DownloadManager downloadManager = new DownloadManager.Builder("downloadManager") .build(context);- Construct the request body object.
// Replace it with the URL of the resource you need to download.String normalUrl = "https://gdown.baidu.com/data/wisegame/10a3a64384979a46/ee3710a3a64384979a46542316df73d4.apk";// Replace with the destination address you want to save.String downloadFilePath = context.getExternalCacheDir().getPath() + File.separator + "test.apk";// 构造GET请求体对象.GetRequest getRequest = DownloadManager.newGetRequestBuilder() .filePath(downloadFilePath) .url(normalUrl) .build();- 创建FileRequestCallbackRequest callback object.
FileRequestCallback callback = new FileRequestCallback() { @Override public GetRequest onStart(GetRequest request) { // This method is called when the file download starts. Log.i(TAG, "activity new onStart:" + request); return request; } @Override public void onProgress(GetRequest request, Progress progress) { // This method is called back when the file download progress changes. Log.i(TAG, "onProgress:" + progress); } @Override public void onSuccess(Response<GetRequest, File, Closeable> response) { // Callback to this method when the file download is successful. String filePath = ""; if (response.getContent() != null) { filePath = response.getContent().getAbsolutePath(); } Log.i(TAG, "onSuccess:" + filePath); } @Override public void onException(GetRequest request, NetworkException exception, Response<GetRequest, File, Closeable> response) { // A network exception occurred during the file download process,or the request is suspended、This method is called back when canceled. if (exception instanceof InterruptedException) { String errorMsg = "onException for paused or canceled"; Log.w(TAG, errorMsg); } else { String errorMsg = "onException for:" + request.getId() + " " + Log.getStackTraceString(exception); Log.e(TAG, errorMsg); } }};- 使用DownloadManagerStart the download task and verify that the download task starts successfully.
当Result的getCodeThe return value and static variable obtained by the methodResult.SUCCESSIf they are consistent, the file download task starts successfully.
Result result = downloadManager.start(getRequest, callback);if (result.getCode() != Result.SUCCESS) { // 当通过result获取到的值为Result.SUCCESS时,The download task starts successfully,否则启动失败. Log.e(TAG, “start download task failed:” + result.getMessage());}- File download status callback.
When the file download status changes,步骤4创建的FileRequestCallbackThe different methods of the request callback object will be called.
• When the file starts downloading,onStart方法会被调用.
• When the file download progress changes,onProgress方法会被调用,And can be called by parsingProgress对象,获取下载进度.
• When an exception occurs in the file download task,onException方法会被调用.
- Verify the download result.
After the file is downloaded successfully, it will call back to the step4创建的FileRequestCallbackThe request callback objectonSuccess方法,You can view the files you downloaded in the phone memory according to the download path you set.
了解更多详情>>
访问华为开发者联盟官网
获取开发指导文档
华为移动服务开源仓库地址:GitHub、Gitee
关注我们,第一时间了解 HMS Core 最新技术资讯~
边栏推荐
- 2022-08-03 Oracle executes slow SQL-Q17 comparison
- override学习(父类和子类)
- [RYU] rest_router.py source code analysis
- 关于IDO预售系统开发技术讲解丨浅谈IDO预售合约系统开发原理分析
- Creo9.0 绘制中心线
- 工作小计 QT打包
- utils 定时器
- What is memoization and what is it good for?
- LabVIEW code generation error 61056
- navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication
猜你喜欢

Boss: There are too many systems in the company, can you realize account interoperability?

SPOJ 2774 Longest Common Substring(两串求公共子串 SAM)

禾匠编译错误记录

获国际权威认可 | 云扩科技入选《RPA全球市场格局报告,Q3 2022》

最小化安装debian11

Scala基础【正则表达式、框架式开发原则】

On the Qixi Festival of 2022, I will offer 7 exquisite confession codes, and at the same time teach you to quickly change the source code for your own use

BMN: Boundary-Matching Network for Temporal Action Proposal Generation阅读笔记

ML之interpret:基于titanic泰坦尼克是否获救二分类预测数据集利用interpret实现EBC模型可解释性之全局解释/局部解释案例

HCIP BGP实验报告
随机推荐
【LeetCode】最长公共子序列(动态规划)
Summary bug 】 【 Elipse garbled solution project code in Chinese!
使用tf.image.resize() 和tf.image.resize_with_pad()调整图像大小
HCIP BGP lab report
With the rise of concepts such as metaverse and web3.0, many digital forms such as digital people and digital scenes have begun to appear.
栈的压入、弹出序列
1067 Sort with Swap(0, i)
HDU 5655 CA Loves Stick
FinClip最易用的智能电视小程序
Diazo Biotin-PEG3-DBCO | Diazo Compound Modified Biotin-Tripolyethylene Glycol-Dibenzocyclooctyne
Zilliz 2023 Fall Campus Recruitment Officially Launched!
[MySQL Advanced] Creation and Management of Databases and Tables
navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication
禾匠编译错误记录
golang写的存储引擎,基于b+树,mmap
一个函数有多少种调用方式?
完全二叉树问题
utlis thread pool
(PC+WAP)织梦模板螺钉手柄类网站
Analysys Analysis: The transaction scale of China's online retail B2C market in Q2 2022 will reach 2,344.47 billion yuan