# okdownload **Repository Path**: HarmonyOS-tpc/okdownload ## Basic Information - **Project Name**: okdownload - **Description**: A Reliable, Flexible, Fast and Powerful download engine. - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 6 - **Forks**: 1 - **Created**: 2021-04-15 - **Last Updated**: 2025-05-02 ## Categories & Tags **Categories**: harmony, web-dev-toolkits **Tags**: None ## README # OkDownload A Reliable, Flexible, Fast and Powerful download engine. ## 集成配置 ### 方法一: ``` 以module方式导入okdownload,okdownload-breakpoint-sqlite,okdownload-connection-okhttp,okdownload-filedownloader到自己鸿蒙项目中;并使用下面的方式依赖 implementation project(':okdownload') implementation project(':okdownload-breakpoint-sqlite') implementation project(':okdownload-connection-okhttp') implementation project(':okdownload-filedownloader') 另外okdownload module中必须添加ohos.jar的依赖,否则编译不通过,格式如下所示: api files('D:\\HOSDEMO\\ohosjar\\ohos.jar') 意味着需要把SDK中的ohos.jar复制出来到D盘后,将上述路径更换为你的ohos.jar的实际本地路径 ``` ### 方法二: ``` 编译这些module生成jar放进libs中 步骤:点击右侧gradle,选择对应的module;比如okdownload,然后点击Tasks展开,再点击jar即生成; 生成的jar包在对应的module下面的build\libs中 引入:将生成jar包放入对应entry或者module的libs目录中 ``` ### 方法三 ``` 添加中心仓库 allprojects{ repositories{ mavenCentral() } } 按照需要添加如下依赖配置 implementation 'io.openharmony.tpc.thirdlib:okdownload-core:1.0.1' implementation 'io.openharmony.tpc.thirdlib:okdownload-breakpoint-sqlite:1.0.1' implementation 'io.openharmony.tpc.thirdlib:okdownload-connection-okhttp:1.0.1' implementation 'io.openharmony.tpc.thirdlib:okdownload-filedownloader:1.0.1' ``` ### jar包使用注意事项 ``` 使用okdownload-connection-okhttp.jar必须自行依赖okhttp三方库 具体版本查看指定module ``` ### 不要忘记在你的entry的config.json中添加网络权限(其他初始化配置见entry的OkDownloadApp.java) ``` "reqPermissions": [ { "name": "ohos.permission.INTERNET" } ] ``` ## I. Task Start and Cancel ### 1. Start a task ``` task = new DownloadTask.Builder(url, parentFile) .setFilename(filename) // the minimal interval millisecond for callback progress .setMinIntervalMillisCallbackProcess(30) // do re-download even if the task has already been completed in the past. .setPassIfAlreadyCompleted(false) .build(); task.enqueue(listener); // cancel task.cancel(); // execute task synchronized task.execute(listener); ``` ### 2. Start tasks ``` // This method is optimize specially for bunch of tasks DownloadTask.enqueue(tasks, listener); // cancel, this method is also optmize specially for bunch of tasks DownloadTask.cancel(tasks); ``` ## II. Queue Build, Start and Stop ``` DownloadContext.Builder builder = new DownloadContext.QueueSet() .setParentPathFile(parentFile) .setMinIntervalMillisCallbackProcess(150) .commit(); builder.bind(url1); builder.bind(url2).addTag(key, value); builder.bind(url3).setTag(tag); builder.setListener(contextListener); DownloadTask task = new DownloadTask.Builder(url4, parentFile) .setPriority(10).build(); builder.bindSetTask(task); DownloadContext context = builder.build(); context.startOnParallel(listener); // stop context.stop(); ``` ## III. Get State and Info Normally you can get state and info on DownloadListener. ### 1. Get download state beyond listener ``` Status status = StatusUtil.getStatus(task) status = StatusUtil.getStatus(url, parentPath, null); status = StatusUtil.getStatus(url, parentPath, filename); boolean isCompleted = StatusUtil.isCompleted(task); isCompleted = StatusUtil.isCompleted(url, parentPath, null); isCompleted = StatusUtil.isCompleted(url, parentPath, filename); Status completedOrUnknown = StatusUtil.isCompletedOrUnknown(task); // If you set tag, so just get tag task.getTag(); task.getTag(xxx); ``` ### 2. Get BreakpointInfo beyond listener ``` // Note: the info will be deleted since task is completed download for data health lifecycle BreakpointInfo info = OkDownload.with().breakpointStore().get(id); info = StatusUtil.getCurrentInfo(url, parentPath, null); info = StatusUtil.getCurrentInfo(url, parentPath, filename); // Since okdownload v1.0.1-SNAPSHOT // the info reference will be cached on the task refrence even if the task is completed download. info = task.getInfo(); ``` ## -------------------------------------------------------------------------------- ### I. Global Control ``` OkDownload.with().setMonitor(monitor); DownloadDispatcher.setMaxParallelRunningCount(3); RemitStoreOnSQLite.setRemitToDBDelayMillis(3000); OkDownload.with().downloadDispatcher().cancelAll(); OkDownload.with().breakpointStore().remove(taskId); ``` ### II. Injection Component If you want to inject your components, please invoke following method before you using OkDownload: ``` OkDownload.Builder builder = new OkDownload.Builder(context) .downloadStore(downloadStore) .callbackDispatcher(callbackDispatcher) .downloadDispatcher(downloadDispatcher) .connectionFactory(connectionFactory) .outputStreamFactory(outputStreamFactory) .downloadStrategy(downloadStrategy) .processFileStrategy(processFileStrategy) .monitor(monitor); OkDownload.setSingletonInstance(builder.build()); ``` ### III. Dynamic Serial Queue ``` DownloadSerialQueue serialQueue = new DownloadSerialQueue(commonListener); serialQueue.enqueue(task1); serialQueue.enqueue(task2); serialQueue.pause(); serialQueue.resume(); int workingTaskId = serialQueue.getWorkingTaskId(); int waitingTaskCount = serialQueue.getWaitingTaskCount(); DownloadTask[] discardTasks = serialQueue.shutdown(); ``` ### IV. Combine Several DownloadListeners ``` DownloadListener listener1 = new DownloadListener1(); DownloadListener listener2 = new DownloadListener2(); DownloadListener combinedListener = new DownloadListenerBunch.Builder() .append(listener1) .append(listener2) .build(); DownloadTask task = new DownloadTask.build(url, file).build(); task.enqueue(combinedListener); ``` ### V. Dynamic Change Listener For tasks ``` // all attach or detach is based on the id of Task in fact. UnifiedListenerManager manager = new UnifiedListenerManager(); DownloadListener listener1 = new DownloadListener1(); DownloadListener listener2 = new DownloadListener2(); DownloadListener listener3 = new DownloadListener3(); DownloadListener listener4 = new DownloadListener4(); DownloadTask task = new DownloadTask.build(url, file).build(); manager.attachListener(task, listener1); manager.attachListener(task, listener2); manager.detachListener(task, listener2); // all listeners added for this task will be removed when task is end. manager.addAutoRemoveListenersWhenTaskEnd(task.getId()); // enqueue task to start. manager.enqueueTaskWithUnifiedListener(task, listener3); manager.attachListener(task, listener4); ``` ### VI. Config Special Profile for Task ``` DownloadTask.Builder builder = new DownloadTask.Builder(url, file); // Set the minimum internal milliseconds of progress callbacks to 100ms.(default is 3000) builder.setMinIntervalMillisCallbackProcess(100); // set the priority of the task to 10, higher means less time to wait to download.(default is 0) builder.setPriority(10); // set the read buffer to 8192 bytes for the response input-stream.(default is 4096) builder.setReadBufferSize(8192); // set the flush buffer to 32768 bytes for the buffered output-stream.(default is 16384) builder.setFlushBufferSize(32768); // set this task allow using 5 connections to download data. builder.setConnectionCount(5); // build the task. DownloadTask task = builder.build(); ``` # LICENSE ``` Copyright (c) 2017 LingoChamp Inc. 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. ```