当前位置:网站首页>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 最新技术资讯~
边栏推荐
- BMN: Boundary-Matching Network for Temporal Action Proposal Generation Reading Notes
- 【LeetCode】最长回文子序列(动态规划)
- RPA power business automation super order!
- What is memoization and what is it good for?
- Software testing is seriously involution, how to improve your competitiveness?
- Zilliz 2023 Fall Campus Recruitment Officially Launched!
- 《数字经济全景白皮书》金融数字用户篇 重磅发布!
- What is Adobe?
- Creo 9.0二维草图的诊断:重叠几何
- MCS-51单片机,定时1分钟,汇编程序
猜你喜欢
End-to-End Lane Marker Detection via Row-wise Classification
软测人每个阶段的薪资待遇,快来康康你能拿多少?
云平台建设解决方案
node连接mysql数据库报错:Client does not support authentication protocol requested by server
【day6】类与对象、封装、构造方法
BMN: Boundary-Matching Network for Temporal Action Proposal Generation阅读笔记
完全二叉树问题
"Digital Economy Panorama White Paper" Financial Digital User Chapter released!
重发布实验报告
[Paper Reading] TRO 2021: Fail-Safe Motion Planning for Online Verification of Autonomous Vehicles Using Conve
随机推荐
软件测试内卷严重,如何提升自己的竞争力呢?
Scala basics [regular expressions, framework development principles]
Zilliz 2023 秋季校园招聘正式启动!
The development status of cloud computing at home and abroad
2022-08-03 Oracle executes slow SQL-Q17 comparison
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.
静态文件快速建站
2022/8/3 考试总结
rosbridge-WSL2 && carla-win11
Boss: There are too many systems in the company, can you realize account interoperability?
Testng监听器
Why do we need callbacks
ML之yellowbrick:基于titanic泰坦尼克是否获救二分类预测数据集利用yellowbrick对LoR逻辑回归模型实现可解释性(阈值图)案例
Testng listener
redis持久化方式
utlis 线程池
"Digital Economy Panorama White Paper" Financial Digital User Chapter released!
FinClip最易用的智能电视小程序
utlis thread pool
(PC+WAP)织梦模板不锈钢类网站