### Initialize FileDownloader in Application Source: https://github.com/lingochamp/filedownloader/blob/master/README-zh.md Demonstrates the global initialization of the FileDownloader engine. It explains two methods: `FileDownloader.setupOnApplicationOnCreate(application)` for custom component registration and `FileDownloader.setup(Context)` for basic setup. Both methods are fast and do not start the download service. ```java FileDownloader.setupOnApplicationOnCreate(application); // or FileDownloader.setup(Context); ``` -------------------------------- ### Setup FileDownloader with Custom Components (Java) Source: https://github.com/lingochamp/filedownloader/wiki/Customizable-Component Demonstrates how to initialize FileDownloader with custom database, output stream, and connection components. This method is typically called in the Application's onCreate method. ```java FileDownloader.setupOnApplicationOnCreate(this) .database(/*You can put your customized database component here*/) .outputStreamCreator(/*You can put your customized output-stream component here*/) .connectionCreator(/*You can put your customized connection component here*/) .commit(); ``` -------------------------------- ### FileDownloader Setup and Initialization Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Initializes the FileDownloader library. `setup(Context)` should be called before any other FileDownloader methods. `setupOnApplicationOnCreate(application)` is for custom component registration, otherwise `setup(Context)` is sufficient. ```java FileDownloader.setup(context); // or for custom components: FileDownloader.setupOnApplicationOnCreate(application).initCustomMaker(); ``` -------------------------------- ### Add FileDownloader Dependency to Gradle Source: https://github.com/lingochamp/filedownloader/wiki/Initialization Add the FileDownloader library as an implementation dependency in your project's `build.gradle` file. This makes the library's functionality available for use in your application. ```groovy dependencies { implementation 'com.liulishuo.filedownloader:library:1.7.4' } ``` -------------------------------- ### Create and Start File Download with Headers - Java Source: https://github.com/lingochamp/filedownloader/wiki/Start-downloading Initiates a file download task using the FileDownloader API. This example shows how to set the download URL, destination path, a listener for download events, and add custom headers to the request before starting the download. ```java FileDownloader.getImpl().create(url) .setPath(path) .setListener(listener) .addHeader(name1,value1) .addHeader(name2,value2) .start(); ``` -------------------------------- ### Initialize FileDownloader in Android Application Source: https://github.com/lingochamp/filedownloader/wiki/Initialization Initialize the FileDownloader library before its first use. You can either call `FileDownloader.setupOnApplicationOnCreate(application)` in your `Application#onCreate` for custom component registration or `FileDownloader.setup(Context)` at any point before usage. Both methods cache necessary context and custom maker variables without performing extensive operations. ```java FileDownloader.setupOnApplicationOnCreate(application).initCustomMaker(); ``` ```java FileDownloader.setup(context); ``` -------------------------------- ### Create and Start Download Tasks Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Creates a new download task for a given URL and starts the download queue. The `start` method can be used with a listener and a boolean to indicate if the queue should be processed serially. Optimizations like `setCallbackProgressTimes(0)` can be used for performance. ```java FileDownloadTask task = FileDownloader.create(url); task.setPath(path); task.start(listener, isSerial); ``` -------------------------------- ### FileDownloader Initialization and Basic Usage Source: https://github.com/lingochamp/filedownloader/wiki/BaseDownloadTask This section covers the basic initialization and core methods for starting a download task. ```APIDOC ## FileDownloader Initialization and Basic Usage ### Description Provides methods to initialize a download task, set the save path, attach a listener, and start the download. ### Method POST ### Endpoint /filedownloader ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (String) - Required - The URL of the file to download. - **path** (String) - Optional - The absolute path or directory to save the downloaded file. - **listener** (Object) - Optional - A listener to callback download status. ### Request Example ```json { "url": "http://example.com/file.zip", "path": "/sdcard/downloads/", "listener": { "onProgress": "(downloaded, total) => console.log(`Progress: ${downloaded}/${total}`)", "onCompleted": "() => console.log('Download completed')" } } ``` ### Response #### Success Response (200) - **taskId** (String) - The unique ID of the download task. #### Response Example ```json { "taskId": "task_12345" } ``` ``` -------------------------------- ### Start File Download with Detailed Listener - Java Source: https://github.com/lingochamp/filedownloader/wiki/Start-downloading Demonstrates starting a file download task with a comprehensive listener implementation. This allows for granular control and monitoring of various download stages, including pending, started, connected, progress, block completion, retry, completed, paused, error, and warning states. ```java FileDownloader.getImpl().create(url) .setPath(path) .setListener(new FileDownloadListener() { @Override protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void started(BaseDownloadTask task) { } @Override protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) { } @Override protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void blockComplete(BaseDownloadTask task) { } @Override protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) { } @Override protected void completed(BaseDownloadTask task) { } @Override protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void error(BaseDownloadTask task, Throwable e) { } @Override protected void warn(BaseDownloadTask task) { } }).start(); ``` -------------------------------- ### Start Download Task Queue with FileDownloadListener (Java) Source: https://github.com/lingochamp/filedownloader/wiki/Start-downloading This snippet shows how to start a download task queue using a single `FileDownloadListener` and the `FileDownloader.getImpl().start()` method. It supports both serial and parallel execution by passing a boolean flag. This approach is suitable for simpler queue management scenarios where a common listener handles all tasks. ```java final FileDownloadListener queueTarget = new FileDownloadListener() { @Override protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) { } @Override protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void blockComplete(BaseDownloadTask task) { } @Override protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) { } @Override protected void completed(BaseDownloadTask task) { } @Override protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void error(BaseDownloadTask task, Throwable e) { } @Override protected void warn(BaseDownloadTask task) { } }; // THE FIRST WAY: //for (String url : URLS) { // FileDownloader.getImpl().create(url) // .setCallbackProgressTimes(0) // why do this? in here i assume do not need for each task callback `FileDownloadListener#progress`, // we just consider which task will complete. so in this way reduce ipc will be effective optimization // .setListener(queueTarget) // .asInQueueTask(); // .enqueue(); //} //if(serial){ // To form a queue with the same queueTarget and execute them linearly // FileDownloader.getImpl().start(queueTarget, true); // } // if(parallel){ // To form a queue with the same queueTarget and execute them in parallel // FileDownloader.getImpl().start(queueTarget, false); //} ``` -------------------------------- ### Start, Pause, and Control Task Execution Source: https://github.com/lingochamp/filedownloader/wiki/BaseDownloadTask Core methods for managing the lifecycle of a download task. `start()` initiates the download, `pause()` halts it, and `isUsing()` checks if the task is currently active in the engine. ```java task.start(); ``` ```java task.pause(); ``` ```java boolean isTaskUsed = task.isUsing(); ``` -------------------------------- ### FileDownloader Task Management Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Methods for creating, starting, pausing, and clearing download tasks. ```APIDOC ## FileDownloader Task Management ### Description Methods for creating, starting, pausing, and clearing download tasks. ### Method `create(url:String)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.create("http://example.com/file.zip"); ``` ### Response Returns a `FileDownloadTask` object. --- ## FileDownloader Task Management ### Description Starts the download queue by the same listener. `setCallbackProgressTimes(0)` can optimize by not calling `FileDownloadListener#progress` for each task. ### Method `start(listener:FileDownloadListener, isSerial:boolean)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.start(myListener, true); ``` ### Response None --- ## FileDownloader Task Management ### Description Pauses the download queue by the same listener. ### Method `pause(listener:FileDownloadListener)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.pause(myListener); ``` ### Response None --- ## FileDownloader Task Management ### Description Pauses all download tasks. ### Method `pauseAll()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.pauseAll(); ``` ### Response None --- ## FileDownloader Task Management ### Description Pauses a specific download task by its ID. ### Method `pause(downloadId)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.pause(123); ``` ### Response None --- ## FileDownloader Task Management ### Description Clears the data associated with a task ID from the FileDownloader database. ### Method `clear(downloadId, targetFilePath)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.clear(123, "/path/to/file"); ``` ### Response None ``` -------------------------------- ### Add Return Value to FileDownloader#start (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Enhances usability by adding a boolean return value to `FileDownloader#start(FileDownloader, boolean)` to indicate whether the task download was successfully initiated. Closes #215. ```Java FileDownloader#start(FileDownloader, boolean) ``` -------------------------------- ### Create and Configure a Download Task Source: https://github.com/lingochamp/filedownloader/wiki/BaseDownloadTask This snippet demonstrates how to initiate a download task by creating an instance using a URL, setting the save path, attaching a listener for status callbacks, and starting the download process. It's a fundamental pattern for using the FileDownloader library. ```java FileDownloader.create(URL) .setPath(xxx) .setListener(xxx) .start(); ``` -------------------------------- ### Initialize FileDownloader with Custom OutputStream Source: https://github.com/lingochamp/filedownloader/wiki/Optimize-Tutorial Example of initializing FileDownloader with a custom output stream creator, specifically FileDownloadBufferedOutputStream. This was previously recommended for improved download speed due to buffered I/O, but is now NOT recommended as it prevents seek operations and thus multi-connection downloads. ```java FileDownloader.init(getApplicationContext(), new DownloadMgrInitialParams.InitCustomMaker() .outputStreamCreator(new FileDownloadBufferedOutputStream.Creator())); ``` -------------------------------- ### FileDownloader Connection Strategy Source: https://github.com/lingochamp/filedownloader/wiki/Customizable-Component Defines the default connection count strategy based on file size. This strategy can be customized using `ConnectionCountAdapter`. ```text - one connection: file length [0, 1MB) - two connections: file length [1MB, 5MB) - three connections: file length [5MB, 50MB) - four connections: file length [50MB, 100MB) - five connections: file length [100MB, -) ``` -------------------------------- ### Start Download Task Queue with FileDownloadQueueSet (Java) Source: https://github.com/lingochamp/filedownloader/wiki/Start-downloading This snippet demonstrates an alternative approach using `FileDownloadQueueSet` to manage download queues. It allows for more advanced configurations such as disabling progress callbacks for individual tasks and setting auto-retry times. The `FileDownloadQueueSet` can then initiate downloads either sequentially or in parallel. ```java final FileDownloadQueueSet queueSet = new FileDownloadQueueSet(downloadListener); final List tasks = new ArrayList<>(); for (int i = 0; i < count; i++) { tasks.add(FileDownloader.getImpl().create(Constant.URLS[i]).setTag(i + 1)); } queueSet.disableCallbackProgressTimes(); // Do not need for each task callback `FileDownloadListener#progress`, // We just consider which task will complete. so in this way reduce ipc will be effective optimization. // Each task will auto retry 1 time if download fail. queueSet.setAutoRetryTimes(1); if (serial) { // Start downloading in serial order. queueSet.downloadSequentially(tasks); // If your tasks are not a list, invoke such following will more readable: // queueSet.downloadSequentially( // FileDownloader.getImpl().create(url).setPath(...), // FileDownloader.getImpl().create(url).addHeader(...,...), // FileDownloader.getImpl().create(url).setPath(...) // ); } if (parallel) { // Start parallel download. queueSet.downloadTogether(tasks); // If your tasks are not a list, invoke such following will more readable: // queueSet.downloadTogether( // FileDownloader.getImpl().create(url).setPath(...), // FileDownloader.getImpl().create(url).setPath(...), // FileDownloader.getImpl().create(url).setSyncCallback(true) // ); } queueSet.start(); ``` -------------------------------- ### FileDownloadListener Callback Flow Source: https://github.com/lingochamp/filedownloader/blob/master/README-zh.md Illustrates the typical sequence of callbacks for a FileDownloadListener during a download process, including states like pending, started, connected, progress, and completion. ```mermaid graph LR A[pending] --> B(started) B --> C(connected) C --> D{progress} D --> E(blockComplete) E --> F(completed) subgraph Termination States G[paused] H[error] I[warn] end D --> G D --> H D --> I subgraph Reused File Scenario J[blockComplete] K[completed] end L(isReusedOldFile) --> J J --> K ``` -------------------------------- ### FileDownloader Configuration Properties Source: https://github.com/lingochamp/filedownloader/wiki/filedownloader.properties This snippet shows example properties for customizing the FileDownloader Engine. These properties are used in a `filedownloader.properties` file within the project's assets folder to control various aspects of the download process. They are written in a `keyword=value` format. ```properties http.lenient=false process.non-separate=false download.min-progress-step=65536 download.min-progress-time=2000 download.max-network-thread-count=3 file.non-pre-allocation=false broadcast.completed=false ``` -------------------------------- ### Manage Download Tasks with FileDownloadQueueSet (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/README-zh.md This snippet demonstrates using FileDownloadQueueSet to manage download tasks, allowing for sequential or parallel execution. It shows how to create tasks, add them to a queue set, disable progress callbacks, set auto-retry, and then initiate downloads either sequentially or together. Finally, it calls start() to begin the download process. ```java final FileDownloadQueueSet queueSet = new FileDownloadQueueSet(downloadListener); final List tasks = new ArrayList<>(); for (int i = 0; i < count; i++) { tasks.add(FileDownloader.getImpl().create(Constant.URLS[i]).setTag(i + 1)); } queueSet.disableCallbackProgressTimes(); // Disable progress callbacks for queue tasks // Auto-retry tasks on download failure queueSet.setAutoRetryTimes(1); if (serial) { // Sequential execution of the task queue queueSet.downloadSequentially(tasks); // Alternative for non-list tasks: // queueSet.downloadSequentially( // FileDownloader.getImpl().create(url).setPath(...), // FileDownloader.getImpl().create(url).addHeader(...,...), // FileDownloader.getImpl().create(url).setPath(...) // ); } if (parallel) { // Parallel execution of the task queue queueSet.downloadTogether(tasks); // Alternative for non-list tasks: // queueSet.downloadTogether( // FileDownloader.getImpl().create(url).setPath(...), // FileDownloader.getImpl().create(url).setPath(...), // FileDownloader.getImpl().create(url).setSyncCallback(true) // ); } // Start the queue queueSet.start() ``` -------------------------------- ### Start Single Task Download Source: https://github.com/lingochamp/filedownloader/blob/master/README-zh.md This Java code snippet illustrates how to initiate a single file download using FileDownloader. It shows how to create a download task, set the download path, and attach a `FileDownloadListener` to handle various download events such as pending, connection, progress, completion, and errors. ```java FileDownloader.getImpl().create(url) .setPath(path) .setListener(new FileDownloadListener() { @Override protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) { } @Override protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void blockComplete(BaseDownloadTask task) { } @Override protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) { } @Override protected void completed(BaseDownloadTask task) { } @Override protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void error(BaseDownloadTask task, Throwable e) { } @Override protected void warn(BaseDownloadTask task) { } }).start(); ``` -------------------------------- ### Fix Starting Linear Downloads for Duplicate Listeners (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Corrects an issue where two queue tasks with the same `FileDownloadListener` might not start properly. The fix involves collecting unbound tasks for initiation rather than relying solely on the listener. Closes #233. ```Java FileDownloadListener BaseDownloadTask ``` -------------------------------- ### FileDownloadProperties Java Class Example Source: https://github.com/lingochamp/filedownloader/wiki/filedownloader.properties This Java code snippet demonstrates how file download properties might be handled within the FileDownloader library. It shows the internal structure and potential parsing of configuration values, indicating how the properties file translates into operational settings. ```java package com.liulishuo.filedownloader.util; public class FileDownloadProperties { public static final String KEY_HTTP_LENIENT = "http.lenient"; public static final String KEY_PROCESS_NON_SEPARATE = "process.non-separate"; public static final String KEY_DOWNLOAD_MIN_PROGRESS_STEP = "download.min-progress-step"; public static final String KEY_DOWNLOAD_MIN_PROGRESS_TIME = "download.min-progress-time"; public static final String KEY_DOWNLOAD_MAX_NETWORK_THREAD_COUNT = "download.max-network-thread-count"; public static final String KEY_FILE_NON_PRE_ALLOCATION = "file.non-pre-allocation"; public static final String KEY_BROADCAST_COMPLETED = "broadcast.completed"; // ... other methods and fields ... } ``` -------------------------------- ### Start, Pause, and Manage Download Tasks Source: https://github.com/lingochamp/filedownloader/blob/master/README-zh.md Initiate, pause, or convert download tasks into queue tasks. Retrieve task-specific information like ID, URL, progress, and status. ```java BaseDownloadTask task = ...; task.start(); task.pause(); InQueueTask queueTask = task.asInQueueTask(); queueTask.enqueue(); int taskId = task.getId(); String url = task.getUrl(); long downloadedBytes = task.getSoFarBytes(); int status = task.getStatus(); ``` -------------------------------- ### FileDownloadMonitor: Global Monitor Management (TypeScript) Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloadMonitor Manages a global monitor for download statistics and debugging. Allows setting, releasing, and getting the global monitor. Dependencies include IMonitor and Download Engine. ```typescript class FileDownloadMonitor { setGlobalMonitor(monitor: IMonitor): void; releaseGlobalMonitor(): void; getMonitor(): IMonitor | null; } interface IMonitor { onRequestStart(count: number, serial: boolean, lis: FileDownloadListener): void; onRequestStart(task: BaseDownloadTask): void; onTaskBegin(task: BaseDownloadTask): void; onTaskStarted(task: BaseDownloadTask): void; onTaskOver(task: BaseDownloadTask): void; } ``` -------------------------------- ### Global Monitoring with FileDownloadMonitor Source: https://github.com/lingochamp/filedownloader/blob/master/README-zh.md Implement a global monitor to observe and log download events at various stages, such as request start, task beginning, and task completion. Allows for centralized debugging and metrics. ```java IMonitor monitor = new IMonitor() { @Override public void onRequestStart(BaseDownloadTask task) { // Handle single task start } // Other IMonitor methods... }; FileDownloadMonitor.setGlobalMonitor(monitor); // To release: // FileDownloadMonitor.releaseGlobalMonitor(); ``` -------------------------------- ### FileDownloader Task Control Source: https://github.com/lingochamp/filedownloader/wiki/BaseDownloadTask Control the execution of a download task, such as starting, pausing, or retrying. ```APIDOC ## FileDownloader Task Control ### Description Provides methods to control the lifecycle of a download task, including starting, pausing, and re-downloading. ### Method POST ### Endpoint /filedownloader/control ### Parameters #### Path Parameters None #### Query Parameters - **taskId** (String) - Required - The ID of the download task. #### Request Body - **action** (String) - Required - The action to perform ('start', 'pause', 'retry'). - **forceReDownload** (Boolean) - Optional - If true, forces a re-download even if the file exists. ### Request Example ```json { "taskId": "task_12345", "action": "start", "forceReDownload": true } ``` ### Response #### Success Response (200) - **message** (String) - Success message. #### Response Example ```json { "message": "Task started successfully." } ``` ``` -------------------------------- ### Installation Dependency for FileDownloader Source: https://github.com/lingochamp/filedownloader/blob/master/README.md This snippet shows how to add the FileDownloader library dependency to your Android project's build.gradle file. It ensures that the latest stable version of the library is included in your project. ```groovy dependencies { implementation 'com.liulishuo.filedownloader:library:1.7.7' } ``` -------------------------------- ### Handle IllegalStateException on Queue Task Restart (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Fixes a bug where starting queue tasks before the service is connected could lead to an `IllegalStateException` when the service later attempts to restart them. Closes #307. ```Java FileDownloader IllegalStateException ``` -------------------------------- ### Get Download Task Information Source: https://github.com/lingochamp/filedownloader/wiki/BaseDownloadTask Retrieve various details about the download task, including its unique ID, URL, path, listener, current status, bytes downloaded, total bytes, and any associated exception. ```java long downloadId = task.getId(); ``` ```java String downloadUrl = task.getUrl(); ``` ```java String savePath = task.getPath(); ``` ```java FileDownloadListener listener = task.getListener(); ``` ```java int status = task.getStatus(); ``` ```java long soFarBytes = task.getSoFarBytes(); ``` ```java long totalBytes = task.getTotalBytes(); ``` ```java Throwable exception = task.getEx(); ``` -------------------------------- ### Get Download Status by ID or URL/Path (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Provides `FileDownloader#getStatus(id:int, path:String)` and `FileDownloader#getStatus(url:String, path:String)` to retrieve the download status of a task using its ID or URL and path combination. Refs #176. ```Java FileDownloader#getStatus(id:int, path:String) FileDownloader#getStatus(url:String, path:String) ``` -------------------------------- ### FileDownloader Initialization Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Methods for setting up and configuring the FileDownloader library. ```APIDOC ## FileDownloader Initialization ### Description Methods for setting up and configuring the FileDownloader library. ### Method `setup(Context)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.setup(context); ``` ### Response None --- ## FileDownloader Initialization ### Description Initializes FileDownloader with custom components. Use `setup(Context)` if no customization is needed. ### Method `setupOnApplicationOnCreate(application)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.setupOnApplicationOnCreate(application).registerCustomMaker(...); ``` ### Response Returns an initializer for custom component registration. ``` -------------------------------- ### FileDownloader Listener Configuration Source: https://github.com/lingochamp/filedownloader/wiki/BaseDownloadTask Set up callbacks to monitor the download progress and status. ```APIDOC ## FileDownloader Listener Configuration ### Description Methods to attach a listener to receive notifications about download status changes, including progress, completion, and errors. ### Method POST ### Endpoint /filedownloader/listener ### Parameters #### Path Parameters None #### Query Parameters - **taskId** (String) - Required - The ID of the download task. #### Request Body - **listener** (Object) - Required - An object containing callback functions for different download states (e.g., `onProgress`, `onCompleted`, `onError`). ### Request Example ```json { "taskId": "task_12345", "listener": { "onPending": "() => console.log('Download pending')", "onProgress": "(downloaded, total) => console.log(`Progress: ${downloaded}/${total}`)", "onCompleted": "() => console.log('Download completed')", "onError": "(error) => console.error('Download error:', error)" } } ``` ### Response #### Success Response (200) - **message** (String) - Success message. #### Response Example ```json { "message": "Listener configured successfully." } ``` ``` -------------------------------- ### Get Target File Path (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Provides `BaseDownloadTask#getTargetFilePath` to retrieve the final storage path of the target file. Refs #200. ```Java BaseDownloadTask#getTargetFilePath ``` -------------------------------- ### Get Temporary File Path (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Adds `FileDownloadUtils#getTempPath` to retrieve the temporary path for incomplete downloads, appended with `.temp` to the filename. Refs #172. ```Java FileDownloadUtils#getTempPath filename.temp ``` -------------------------------- ### Get Download Speed Source: https://github.com/lingochamp/filedownloader/wiki/BaseDownloadTask Retrieve the download speed for a task. This can be the real-time speed if the download is in progress or the average speed if the download has finished. The speed is reported in KB/s. ```java long speed = task.getSpeed(); ``` -------------------------------- ### Migrate from ready() to asInQueueTask() and enqueue() (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Introduces `BaseDownloadTask#asInQueueTask():InQueueTask` and deprecates `BaseDownloadTask#ready()`. This change provides a clearer way to designate tasks as queue tasks and enqueue them for execution. Calling `enqueue()` on non-queue tasks will result in an exception. Closes #305. ```Java BaseDownloadTask#ready() BaseDownloadTask#asInQueueTask():InQueueTask InQueueTask#enqueue() DownloadTask#start ``` -------------------------------- ### Get Download Status Ignoring Completed (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Adds `FileDownloader#getStatusIgnoreCompleted(id:int)` which returns `INVALID` if the task is completed, otherwise returns its current status. Refs #176. ```Java FileDownloader#getStatusIgnoreCompleted(id:int) INVALID ``` -------------------------------- ### Get Task Tag Source: https://github.com/lingochamp/filedownloader/wiki/BaseDownloadTask Retrieve the tag object associated with the download task. This allows retrieving previously set tags, useful for identifying or managing tasks based on custom metadata. ```java Object tag = task.getTag(); ``` ```java Object specificTag = task.getTag("myKey"); ``` -------------------------------- ### Check and Ensure FileDownloader Service Binding Source: https://github.com/lingochamp/filedownloader/wiki/QA Provides methods to check if the FileDownloader service is connected and to ensure it is bound, with options for synchronous and asynchronous operations. These methods are useful for optimizing download startup by managing the download service connection. ```java boolean isConnected = FileDownloader.isServiceConnected(); // Ensure service is bound synchronously FileDownloader.insureServiceBind(); // Ensure service is bound asynchronously FileDownloader.insureServiceBindAsync(); // Bind service with a callback FileDownloader.bindService(new Runnable() { @Override public void run() { // Service is bound, proceed with download operations } }); ``` -------------------------------- ### Initializing FileDownloader with Custom Components Source: https://github.com/lingochamp/filedownloader/blob/master/README.md This code demonstrates how to initialize the FileDownloader with custom components using `DownloadMgrInitialParams.InitCustomMaker`. This allows for deeper customization of the download process, such as providing your own connection or output stream implementations. ```java FileDownloader.init(context, new DownloadMgrInitialParams.InitCustomMaker() { @Override public void customize(BaseDownloadTask task) { // Customize task behavior here } @Override public void customize(BaseDownloadReceiver receiver) { // Customize receiver behavior here } @Override public ConnectionCountAdapter fetchConnectionCountAdapter(ConnectionCountAdapter existAdapter) { // Return a custom ConnectionCountAdapter return super.fetchConnectionCountAdapter(existAdapter); } @Override public FileDownloadDatabase fetchFileDownloadDatabase(FileDownloadDatabase existDatabase) { // Return a custom FileDownloadDatabase return super.fetchFileDownloadDatabase(existDatabase); } @Override public FileDownloadOutputStream fetchStream(FileDownloadOutputStream existStream) { // Return a custom FileDownloadOutputStream return super.fetchStream(existStream); } @Override public FileDownloadConnection fetchConnection(FileDownloadConnection existConnection) { // Return a custom FileDownloadConnection return super.fetchConnection(existConnection); } @Override public IdGenerator fetchIdGenerator(IdGenerator existIdGenerator) { // Return a custom IdGenerator return super.fetchIdGenerator(existIdGenerator); } @Override public ForegroundServiceConfig fetchForegroundServiceConfig(ForegroundServiceConfig existConfig) { // Return a custom ForegroundServiceConfig return super.fetchForegroundServiceConfig(existConfig); } }); ``` -------------------------------- ### Low Memory Scenarios Source: https://github.com/lingochamp/filedownloader/blob/master/README-zh.md Explanation of how FileDownloader behaves under low memory conditions for both non-download (UI) processes and download processes. ```APIDOC ## Low Memory Scenarios ### Non-Download Process (Typically UI Process): This process has minimal data and memory usage. **Foreground Process Data Recycling:** Highly unlikely, as the app would likely be dead if foreground data is recycled. **Background Process Data Recycling:** More common. If the UI process is in the background and memory is low, it might be recycled (higher priority than service processes). 1. **Serial Queue Tasks:** If the UI process is recycled, the download process continues the pending task. Tasks not yet pending are interrupted. Experience Impact: Next app launch resumes download from the interrupted point. 2. **Parallel Queue Tasks:** If the UI process is recycled, the download process continues all pending tasks (pending is fast). The UI process won't receive callbacks. Experience Impact: Next app launch resumes downloads normally, receiving all callbacks. ### Download Process: The download process has some memory footprint but is managed. It's a low-probability event for this process to be recycled. Even if recycled, no issues arise. Due to `START_STICKY`, the download process attempts to restart when memory is sufficient. The non-download process reconnects, and downloads resume from where they were interrupted (breakpoint resume) without affecting the user experience. ``` -------------------------------- ### Get Temporary Path for Incomplete Downloads in FileDownloader Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloadUtils Retrieves the designated temporary path used for storing files that are currently in the process of downloading. These files are typically named with a '.temp' extension. ```Java /** * Get the temp path is used for storing the temporary file not completed downloading yet(`filename.temp`) * @return The temporary path string. */ public String getTempPath() ``` -------------------------------- ### FileDownloader Network Configuration Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Methods for configuring network-related settings. ```APIDOC ## FileDownloader Network Configuration ### Description Methods for configuring network-related settings. ### Method `setMaxNetworkThreadCount(count:int)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.setMaxNetworkThreadCount(5); ``` ### Response Sets the maximum number of network threads for simultaneous downloads in FileDownloader. ``` -------------------------------- ### FileDownloader Database Management Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Methods for managing the FileDownloader database. ```APIDOC ## FileDownloader Database Management ### Description Methods for managing the FileDownloader database. ### Method `clearAllTaskData()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.clearAllTaskData(); ``` ### Response Clears all data from the `filedownloader` database. ``` -------------------------------- ### Get ETag and Retry Information Source: https://github.com/lingochamp/filedownloader/wiki/BaseDownloadTask Access the ETag value from the response headers and retrieve information about automatic retries. This includes the total number of retries configured and the current number of retries attempted. ```java String etag = task.getEtag(); ``` ```java int totalRetries = task.getAutoRetryTimes(); ``` ```java int currentRetries = task.getRetryingTimes(); ``` -------------------------------- ### Fix IllegalStateException with Concurrent Tasks and Listeners (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Resolves an `IllegalStateException` that could occur when multiple isolated tasks and queue tasks using the same `listener` object are started concurrently on different threads. Closes #282. ```Java IllegalStateException BaseDownloadTask FileDownloadListener ``` -------------------------------- ### Foreground Mode for Downloads Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Allows configuring the download service to run in the foreground, ensuring it remains active even when the app is removed from recent apps. `startForeground` requires a notification, and `stopForeground` cancels this mode. ```java FileDownloader.startForeground(id, notification); FileDownloader.stopForeground(true); ``` -------------------------------- ### FileDownloadMonitor Source: https://github.com/lingochamp/filedownloader/blob/master/README-zh.md APIs for setting up and managing global monitors to observe download engine events. ```APIDOC ## FileDownloadMonitor ### Description Provides functionality to set, release, and get a global monitor for observing download engine events. ### Methods - **`setGlobalMonitor(monitor: IMonitor)`**: Sets or replaces the global monitor in the download engine. - **`releaseGlobalMonitor()`**: Releases the currently set global monitor. - **`getMonitor()`**: Retrieves the currently set global monitor. #### `FileDownloadMonitor.IMonitor` Interface ### Description An interface for implementing custom monitoring logic. ### Methods - **`onRequestStart(count: int, serial: boolean, lis: FileDownloadListener)`**: Called when starting queue tasks. Provides task count, serial execution flag, and the listener. - **`onRequestStart(task: BaseDownloadTask)`**: Called when starting a single task. - **`onTaskBegin(task: BaseDownloadTask)`**: Called when the engine internally receives and begins processing a task (before `pending` callback). - **`onTaskStarted(task: BaseDownloadTask)`**: Called when a task's runnable starts after transitioning from pending. - **`onTaskOver(task: BaseDownloadTask)`**: Called when a task has completed its entire lifecycle. ``` -------------------------------- ### FileDownloader Status and Information Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Methods for retrieving download status and information. ```APIDOC ## FileDownloader Status and Information ### Description Methods for retrieving download status and information. ### Method `getSoFar(downloadId)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java long downloadedBytes = FileDownloader.getSoFar(123); ``` ### Response Returns the number of bytes downloaded so far for the given download ID. --- ## FileDownloader Status and Information ### Description Retrieves the total file size in bytes for a given download ID. ### Method `getTotal(downloadId)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java long totalBytes = FileDownloader.getTotal(123); ``` ### Response Returns the total file size in bytes. --- ## FileDownloader Status and Information ### Description Retrieves the downloading status of a task, ignoring the completed status. Returns `INVALID` if completed. ### Method `getStatusIgnoreCompleted(downloadId)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java int status = FileDownloader.getStatusIgnoreCompleted(123); ``` ### Response Returns the download status (e.g., `FileDownloadStatus.pending`, `FileDownloadStatus.connected`, `FileDownloadStatus.completed`, `INVALID`). --- ## FileDownloader Status and Information ### Description Retrieves the downloading status of a task using its ID and file path. ### Method `getStatus(id:int, path:String)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java int status = FileDownloader.getStatus(123, "/path/to/file"); ``` ### Response Returns the download status. --- ## FileDownloader Status and Information ### Description Retrieves the downloading status of a task using its URL and file path. ### Method `getStatus(url:String, path:String)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java int status = FileDownloader.getStatus("http://example.com/file.zip", "/path/to/file"); ``` ### Response Returns the download status. ``` -------------------------------- ### Fix Incorrect Download Status for Concurrent Downloads (Java) Source: https://github.com/lingochamp/filedownloader/blob/master/CHANGELOG-ZH.md Ensures accurate download status by deleting the target file when a download truly starts. This prevents scenarios where concurrent downloads of the same task might incorrectly report a completed status. Closes #220. ```Java FileDownloadListener#completed ``` -------------------------------- ### FileDownloader Service Management Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Methods for managing the FileDownloader background service. ```APIDOC ## FileDownloader Service Management ### Description Methods for managing the FileDownloader background service. ### Method `bindService()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.bindService(); ``` ### Response Binds and starts the `:filedownloader` process manually. This is usually handled automatically by the Download Engine when needed. --- ## FileDownloader Service Management ### Description Unbinds and stops the `:filedownloader` process manually. ### Method `unBindService()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.unBindService(); ``` ### Response None --- ## FileDownloader Service Management ### Description Unbinds and stops the `:filedownloader` process if there are no active tasks. ### Method `unBindServiceIfIdle()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.unBindServiceIfIdle(); ``` ### Response None --- ## FileDownloader Service Management ### Description Checks if the `:filedownloader` process has started and is connected. ### Method `isServiceConnected()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java boolean isConnected = FileDownloader.isServiceConnected(); ``` ### Response Returns `true` if the service is connected, `false` otherwise. ``` -------------------------------- ### FileDownloader Foreground Service Source: https://github.com/lingochamp/filedownloader/wiki/FileDownloader Methods for configuring the FileDownloadService to run in foreground mode. ```APIDOC ## FileDownloader Foreground Service ### Description Methods for configuring the FileDownloadService to run in foreground mode. ### Method `startForeground(id:int, notification:Notification)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.startForeground(1, notification); ``` ### Response Configures FileDownloadService to Foreground mode, ensuring it stays alive when the app is removed from recent apps. --- ## FileDownloader Foreground Service ### Description Cancels Foreground mode in FileDownloadService. ### Method `stopForeground(removeNotification:boolean)` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java FileDownloader.stopForeground(true); ``` ### Response None ``` -------------------------------- ### Configure FileDownloader to Run in Main Process Source: https://github.com/lingochamp/filedownloader/wiki/Optimize-Tutorial Set 'process.non-separate=true' in 'filedownloader.properties' to run the FileDownloader service within the main application process. This reduces CPU and I/O overhead from inter-process communication, potentially improving download speed. However, it means the downloader's lifecycle is tied to the main process. ```properties process.non-separate=true ``` -------------------------------- ### FileDownloader Properties Configuration Source: https://github.com/lingochamp/filedownloader/blob/master/README-zh.md Customize FileDownloader behavior by creating a 'filedownloader.properties' file in your project's assets directory. This section outlines the available keywords and their functions. ```APIDOC ## Configuration via `filedownloader.properties` To customize FileDownloader, create a `filedownloader.properties` file in your project's `assets` directory (e.g., `/demo/src/main/assets/filedownloader.properties`). **Format:** `keyword=value` | Keyword | Description | Default Value | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | `http.lenient` | Ignores non-compliant HTTP response headers (e.g., unknown `Transfer-Encoding`) and treats them as chunked. Set to `true` to enable. | `false` | | `process.non-separate` | Runs `FileDownloadService` in the main process instead of a separate `:filedownloader` process. Set to `true` to reduce IPC I/O. | `false` | | `download.min-progress-step` | Minimum buffer size for synchronizing progress to the database and writing to the file. Smaller values increase update frequency and decrease download speed but improve safety against unexpected process termination. | `65536` | | `download.min-progress-time` | Minimum time interval for synchronizing progress to the database and writing to the file. Smaller values increase update frequency and decrease download speed but improve safety against unexpected process termination. | `2000` | | `download.max-network-thread-count` | Maximum number of concurrent network threads for downloading. Range: `[1, 12]`. | `3` | | `file.non-pre-allocation` | Disables pre-allocation of the entire file size (`content-length`) at the start of the download. Set to `true` to disable. | `false` | | `broadcast.completed` | Sends a broadcast upon task completion. Set to `true` to enable. If enabled, register for the `filedownloader.intent.action.completed` action and use `FileDownloadBroadcastHandler` to process the received `Intent`. | `false` | ```