5 Star 1 Fork 0

HarmonyOS-TPC / CoreProgress

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

CoreProgress

This library help to display progress while uploading and downloading file using OkHttp.

CoreProgress includes :

  • Progress while downloading the file using OkHttp.
  • Progress while uploading the file using OkHttp.

Usage Instructions

Sample application require following permissions:

ohos.permission.INTERNET

cleartextTraffic support is disabled by default for HTTP. However, HTTPS is supported by default. To support HTTP, need to add "network" to the config.json file, and set the attribute "cleartextTraffic" to true.

{
  "deviceConfig": {
    "default": {
      "network": {
        "cleartextTraffic": true
      }
    }
  }
}

Download

OkHttpClient okHttpClient = new OkHttpClient();
Request.Builder builder = new Request.Builder();
builder.url(url);
builder.get();
Call call = okHttpClient.newCall(builder.build());
LogUtil.info("TAG", "url : " + url);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException exception) {
        LogUtil.error("TAG", "====onFailure======== e.getMessage() : " + exception.getMessage());
    }
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        LogUtil.info("TAG", "=============onResponse===============");
        LogUtil.info("TAG", "response length:" + response.body().contentLength());
        LogUtil.info("TAG", "Content-Length: " + response.header("Content-Length"));
        ResponseBody responseBody = ProgressHelper.withProgress(response.body(), new ProgressUIListener() {
            // if you don't need this method, don't override this method.
            // It isn't an abstract method, just an empty method.
            @Override
            public void onUIProgressStart(long totalBytes) {
                super.onUIProgressStart(totalBytes);
                LogUtil.info("TAG", "onUIProgressStart:" + totalBytes);
                downloadInfo.setText("onUIProgressStart:" + totalBytes);
            }
            @Override
            public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
                LogUtil.info("TAG", "=============start===============");
                LogUtil.info("TAG", "onUIProgressChanged  totalBytes : " + totalBytes
                        + "  numBytes : " + numBytes + "  percent : " + percent
                        + "  fp : " + (numBytes * 100) / totalBytes + "  speed : " + speed);
                downloadProgeress.setProgressValue((int) ((numBytes * 100) / totalBytes));
                downloadInfo.setText("numBytes:" + numBytes + " bytes totalBytes:" + totalBytes
                        + " bytes percent:" + percent * 100 + " % speed:" + speed * 1000 / 1024 / 1024 + "  MB/s");
            }
            // If you don't need this method, don't override this method.
            // It isn't an abstract method, just an empty method.
            @Override
            public void onUIProgressFinish() {
                super.onUIProgressFinish();
                LogUtil.error("TAG", "onUIProgressFinish");
            }
        });

        BufferedSource source = responseBody.source();
        String path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        File outFile = new File(path + "/temp.mp4");
        outFile.delete();
        outFile.getParentFile().mkdirs();
        outFile.createNewFile();

        BufferedSink sink = Okio.buffer(Okio.sink(outFile));
        source.readAll(sink);
        sink.flush();
        source.close();
    }
});

Upload

String path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
File outFile = new File(path + "/temp.mp4");
String url = "";

OkHttpClient okHttpClient = new OkHttpClient();
Request.Builder builder = new Request.Builder();
builder.url(url);

MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
bodyBuilder.addFormDataPart("test", outFile.getName(), RequestBody.create(outFile, MediaType.parse("video/mp4")));
MultipartBody build = bodyBuilder.build();

RequestBody requestBody = ProgressHelper.withProgress(build, new ProgressUIListener() {
    // If you don't need this method, don't override this method.
    // It isn't an abstract method, just an empty method.
    @Override
    public void onUIProgressStart(long totalBytes) {
        super.onUIProgressStart(totalBytes);
        LogUtil.info("TAG", "onUIProgressStart:" + totalBytes);
    }

    @Override
    public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
        LogUtil.info("TAG", "=============start===============");
        LogUtil.info("TAG", "numBytes:" + numBytes);
        LogUtil.info("TAG", "totalBytes:" + totalBytes);
        LogUtil.info("TAG", "percent:" + percent);
        LogUtil.info("TAG", "speed:" + speed);
        LogUtil.info("TAG", "============= end ===============");
        uploadProgress.setProgressValue((int) ((numBytes * 100) / totalBytes));
        uploadInfo.setText("numBytes:" + numBytes
                + " bytes totalBytes:" + totalBytes
                + " bytes percent:" + percent * 100
                + " % speed:" + speed * 1000 / 1024 / 1024 + "  MB/s");
    }

    // if you don't need this method, don't override this method.
    // It isn't an abstract method, just an empty method.
    @Override
    public void onUIProgressFinish() {
        super.onUIProgressFinish();
        LogUtil.info("TAG", "onUIProgressFinish:");
    }
});
builder.post(requestBody);

Call call = okHttpClient.newCall(builder.build());
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException exception) {
        LogUtil.error("TAG", "=============onFailure===============" + exception.getMessage());
        exception.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        LogUtil.info("TAG", "=============onResponse===============");
        LogUtil.info("TAG", "request headers:" + response.request().headers());
        LogUtil.info("TAG", "response headers:" + response.headers());
    }
});

Callback in original thread

if you don't need callback in UI thread, you can use ProgressListener to callback in your caller's original Thread.

//callback in original thread.
ProgressListener progressListener = new ProgressListener() {
    //if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
    @Override
    public void onProgressStart(long totalBytes) {
        super.onProgressStart(totalBytes);
    }
    @Override
    public void onProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
    }
    //if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
    @Override
    public void onProgressFinish() {
        super.onProgressFinish();
    }
};

Installation Instructions

CoreProgress is dependent on OkHttp.

  1. For using CoreProgress module in your sample application, add below dependencies to generate hap/har:

    Modify entry build.gradle as below :

    dependencies {
    	implementation fileTree(dir: 'libs', include: ['*.har'])
    	implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.1'
        implementation project(path: ':library')
    }
  2. For using CoreProgress in separate application, add the below dependencies and include "CoreProgress.har" in libs folder of "entry" module :

    Modify entry build.gradle as below :

    dependencies {
    	implementation fileTree(dir: 'libs', include: ['*.har'])
    	implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.1'
    }
  3. For using CoreProgress from a remote repository in separate application, add the below dependencies "entry" module :

    Modify entry build.gradle as below :

    dependencies {
    	implementation fileTree(dir: 'libs', include: ['*.har'])
    	implementation 'io.openharmony.tpc.thirdlib:CoreProgress:1.0.1'
    	implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.1'
    }

License

Copyright 2017 区长
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

空文件

简介

This library help to display progress while uploading and downloading file using OkHttp. 展开 收起
Java
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/HarmonyOS-tpc/CoreProgress.git
git@gitee.com:HarmonyOS-tpc/CoreProgress.git
HarmonyOS-tpc
CoreProgress
CoreProgress
master

搜索帮助