Valentine's Day is coming, all kinds of apps have to be busy with new ones, seize the holiday hotspots of Internet products, and carry out event marketing combined with the categories of apps. For example, shopping apps will have big promotions during festivals; travel apps will launch various promotions; short video and photo apps will launch various holiday-limited special effects, exclusive stickers, etc.

Game apps, in particular, have strong social attributes. In festival hotspots, version updates are usually carried out, new skins and new scenes are launched, etc., which involve a lot of content. Sometimes the resources of the version update package are too large, causing users to wait for the update. It takes a long time, which affects the operation promotion and user download experience. At this time, you only need to access the HMS Core Network Kit , which can greatly increase the resource download rate.

HMS Core Network Kit is a basic network service kit that aggregates the best practices of far-field network communication, supplemented by RESTful, file upload/download and other scenario-based interfaces, providing you with easy-to-use, low-latency, high-throughput, and high-security solutions. End-to-cloud transmission channel. In addition to improving the speed and success rate of file upload/download, it can also improve network access speed in URL access network scenarios, reduce invalid network waiting time in weak network environments, and support smooth network migration.

As can be seen from the figure, the download speed is increased by about 40% after the integration of Network Kit.

HMS Core Network Kit first superimposes the self-developed large file congestion control algorithm on the QUIC protocol, and effectively improves the throughput under weak network through efficient concurrent data flow; secondly, intelligent sharding sets different sharding thresholds and The number of shards can increase the download speed as much as possible; at the same time, it also supports concurrent execution and management of multi-tasks, and resumes the transfer of tasks at breakpoints to improve the success rate of downloads. It is suitable for resource loading, event pictures, video downloads, etc. related to new version upgrades, patch upgrades, new scene maps, etc.

Development steps

Before developing, you need to complete the necessary development preparations. For details, please refer to the Network Development Guidance Document .

The SDK integration sample code is as follows:

 dependencies {
    // 使用Network Kit的网络请求功能
    implementation 'com.huawei.hms:network-embedded: 6.0.0.300'
    // 使用Network Kit的文件上传/下载功能
    implementation 'com.huawei.hms:filemanager: 6.0.0.300'
}

Because Network Kit uses the new features of Java 8, such as: Lambda expressions, static interface methods, etc. Therefore, Network Kit needs to add Java 8 environment compilation constraints to Gradle.

Add the following compile configuration to "compileOptions".

 android{
    compileOptions{
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

sample code

File Upload

The file upload function can be realized by the following operations. For detailed development process and code implementation, please refer to codelab (file upload/download integration) and sample code .

  1. When the adaptation version is Android 6.0 (API Level 23) and above, you need to dynamically apply for read and write mobile phone storage permissions (each application only needs to successfully apply once).
 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);
    }
}
  1. Initialize the global upload management class UploadManager .
 UploadManager upManager = (UploadManager) new UploadManager
        .Builder("uploadManager")
        .build(context);
  1. Construct the request body object. Let's take uploading files file1 and file2 as an example.
 Map<String, String> httpHeader = new HashMap<>();
httpHeader.put("header1", "value1");
Map<String, String> httpParams = new HashMap<>();
httpParams.put("param1", "value1");
// 替换成您需要上传的目的地址。
String normalUrl = "https://path/upload";
// 替换成您需要上传的文件的地址。
String filePath1 = context.getString(R.string.filepath1);
// 替换成您需要上传的文件的地址。
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());
}
  1. Create a FileUploadCallback request callback class.
 FileUploadCallback callback = new FileUploadCallback() {
    @Override
    public BodyRequest onStart(BodyRequest request) {
        // 文件上传开始时回调此方法。
        Log.i(TAG, "onStart:" + request);
        return request;
    }


    @Override
    public void onProgress(BodyRequest request, Progress progress) {
        // 文件上传进度变化时回调到此方法。
        Log.i(TAG, "onProgress:" + progress);
    }


    @Override
    public void onSuccess(Response<BodyRequest, String, Closeable> response) {
        // 文件上传成功时回调此方法。
        Log.i(TAG, "onSuccess:" + response.getContent());
    }


    @Override
    public void onException(BodyRequest request, NetworkException exception, Response<BodyRequest, String, Closeable> response) {
        // 文件上传过程中网络发生异常,或请求被取消时回调此方法。
        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);
        }
    }
};
  1. Send a request to upload the specified file, and get whether the upload is started successfully.

When the return value obtained by the getCode method of Result is consistent with the static variable Result.SUCCESS, the file upload task starts successfully.

 Result result = upManager.start(request, callback);
// 上传任务启动是否成功,可以通过Result的getCode()方法获取的返回值是否与静态变量Result.SUCCESS一致来判断。
if (result.getCode() != Result.SUCCESS) {
    Log.e(TAG, result.getMessage());
}
  1. File upload status callback.

When the file upload status changes, different callback methods of the FileUploadCallback object created in step 4 will be called.

• When the file upload starts, the onStart method will be called.

• When the file upload progress changes, the onProgress method will be called, and the upload progress can be obtained by parsing the Progress object of the callback.

• When an exception occurs in the file upload task, the onException method will be called.

  1. Verify the upload result.

After the file is uploaded successfully, it will call back to the onSuccess method of the FileUploadCallback request callback object created in step 4.

file download

The file download function can be realized by the following operations. For the detailed development process and code implementation, please refer to the codelab (file upload/download integration) and sample code .

  1. When the adaptation version is Android 6.0 (API Level 23) and above, you need to dynamically apply for read and write mobile phone storage permissions (each application only needs to successfully apply once).
 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);
    }
}
  1. Initialize the global download management class DownloadManager.
 DownloadManager downloadManager = new DownloadManager.Builder("downloadManager")
             .build(context);
  1. Construct the request body object.
 // 替换成您需要下载的资源地址。
String normalUrl = "https://gdown.baidu.com/data/wisegame/10a3a64384979a46/ee3710a3a64384979a46542316df73d4.apk";
// 替换成您想要保存的目的地址。
String downloadFilePath = context.getExternalCacheDir().getPath() + File.separator + "test.apk";
// 构造GET请求体对象。
GetRequest getRequest = DownloadManager.newGetRequestBuilder()
        .filePath(downloadFilePath)
        .url(normalUrl)
        .build();
  1. Create a FileRequestCallback request callback object.
 FileRequestCallback callback = new FileRequestCallback() {
    @Override
    public GetRequest onStart(GetRequest request) {
        // 文件下载开始时回调此方法。
        Log.i(TAG, "activity new onStart:" + request);
        return request;
    }
 
    @Override
    public void onProgress(GetRequest request, Progress progress) {
        // 文件下载进度变化时回调此方法。
        Log.i(TAG, "onProgress:" + progress);
    }
 
    @Override
    public void onSuccess(Response<GetRequest, File, Closeable> response) {
        // 文件下载成功时回调到此方法。
        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) {
        // 文件下载过程中网络发生异常,或请求被暂停、取消时回调此方法。
        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);
        }
    }
};
  1. Use DownloadManager to start the download task and verify whether the download task starts successfully.

When the return value obtained by the getCode method of Result is consistent with the static variable Result.SUCCESS, the file download task starts successfully.

 Result result = downloadManager.start(getRequest, callback);
if (result.getCode() != Result.SUCCESS) {
    // 当通过result获取到的值为Result.SUCCESS时,则下载任务启动成功,否则启动失败。
    Log.e(TAG, “start download task failed:” + result.getMessage());
}
  1. File download status callback.

When the file download status changes, different methods of the FileRequestCallback request callback object created in step 4 will be called.

• When the file starts to download, the onStart method will be called.

• When the file download progress changes, the onProgress method will be called, and the download progress can be obtained by parsing the Progress object of the callback.

• When an exception occurs in the file download task, the onException method will be called.

  1. Verify the download result.

After the file is downloaded successfully, it will call back to the onSuccess method of the FileRequestCallback request callback object created in step 4, and you can view the file you downloaded in the phone memory according to the download path you set.

Learn more details>>

Visit the official website of Huawei Developer Alliance
Get development guidance documents
Huawei Mobile Services Open Source Warehouse Address: GitHub , Gitee

Follow us to know the latest technical information of HMS Core for the first time~


HarmonyOS_SDK
596 声望11.7k 粉丝

HarmonyOS SDK通过将HarmonyOS系统级能力对外开放,支撑开发者高效打造更纯净、更智能、更精致、更易用的鸿蒙应用,和开发者共同成长。