Download tool based on kotlin and coroutine.

Overview

DownloadX

A multi-threaded download tool written with Coroutine and Kotlin

Read this in other languages: 中文English, Changelog 

Prepare

  • Add jitpack repo:
maven { url 'https://jitpack.io' }
  • Add dependency:
implementation "com.github.ssseasonnn:DownloadX:1.0.1"

Basic Usage

// create download task
val downloadTask = coroutineScope.download("url")

// listen download progress
downloadTask.progress()
    .onEach { binding.button.setProgress(it)  }
    .launchIn(lifecycleScope)

// or listen download state
downloadTask.state()
    .onEach { binding.button.setState(it)  }
    .launchIn(lifecycleScope)

// start download
downloadTask.start()

Create task

  • Specify CoroutineScope

If the download task is limited to the lifecycle of the Activity or Fragment, you can directly use the lifecycleScope of the Activity or Fragment to ensure that the download task ends automatically when the Activity or Fragment is destroyed

lifecycleScope is an extension in androidX, you need to add the following dependencies: implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'

class DemoActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        //When the activity is destroyed, the download task automatically stops
        val downloadTask = lifecycleScope.download("url")
        downloadTask.start()
    }
}

If the download task needs to be shared between multiple activities, or download in the background, then directly use GlobalScope

class DemoActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        //When the activity is destroyed, the download task still continues to download
        val downloadTask = GlobalScope.download("url")
        downloadTask.start()
    }
}
  • Set the file name and save path

Pass directly to the download method:

val downloadTask = GlobalScope.download("url", "saveName", "savePath")

Custom DownloadParam:

val downloadParam = DownloadParam("url", "saveName", "savePath")
val downloadTask = lifecycleScope.download(downloadParam)

By default, we use url as the only indicator of DownloadTask. When you need to change this default behavior, you can customize your own DownloadParam:

class CustomDownloadParam(url: String, saveName: String, savePath: String) : DownloadParam(url, saveName, savePath) {
    override fun tag(): String {
        // Use the file path as a unique identifier
        return savePath + saveName
    }
}

val customDownloadParam = CustomDownloadParam("url", "saveName", "savePath")
val downloadTask = lifecycleScope.download(customDownloadParam)

When multiple pages use the same identifier (for example, the same url) to create a download task, the same DownloadTask will be returned, for example:

// same url
val url = "xxxx"

class DemoActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //Create download task
        val downloadTask = GlobalScope.download(url)

        downloadTask.progress()
            .onEach { progress ->  /* update progress */ }
            .launchIn(lifecycleScope)

        downloadTask.start()
    }
}

class OtherActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //Create a download task with the same url to get the download task created on the previous page
        val downloadTask = GlobalScope.download(url)

        downloadTask.progress()
            .onEach { progress ->  /* update progress */ }
            .launchIn(lifecycleScope)

        downloadTask.start()
    }
}

Based on this, the same download progress and download status can be shared on any number of pages

Progress and State

  • Listen progress only

This method can be used in certain scenarios when only the download progress is needed

val downloadTask = lifecycleScope.download("url")

downloadTask.progress()
    .onEach { progress ->  /* update progress */ }
    .launchIn(lifecycleScope) // using lifecycleScope

downloadTask.start()

Use lifecycleScope to ensure that the monitoring is automatically released when the Activity or Fragment is destroyed

You can set the update interval for the progress() method. The default is to update every 200ms, such as:

downloadTask.progress(500) // Set to update the progress every 500ms
    .onEach { progress ->  
        // update progress
        setProgress(progress)
    }
    .launchIn(lifecycleScope)
  • Listen progress and state

When you need download status and download progress, use this method to get

val downloadTask = lifecycleScope.download("url")

downloadTask.state()
    .onEach { state ->  
        // update state
        setState(state)
        // update progress
        setProgress(state.progress)
    }
    .launchIn(lifecycleScope)

downloadTask.start()

state has the following values:None,Waiting,Downloading,Stopped,Failed,Succeed

Similarly, you can set the progress update interval for the state() method

Start and Stop

  • Start download
downloadTask.start()
  • Stop download
downloadTask.stop()
  • Remove download
downloadTask.remove()

License

Copyright 2021 Season.Zlc

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.
You might also like...
Android Clean Architechture with MVVM, LiveData, Coroutine, Dagger Hilt, Room, DataStore
Android Clean Architechture with MVVM, LiveData, Coroutine, Dagger Hilt, Room, DataStore

MovKu An application that displays a list of popular movies and detail Concepts Tech Stack Kotlin -A modern programming language that makes developers

This Project for how to use  MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture.
This Project for how to use MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture.

Clean-architecture This Project for how to use MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture. Why i should us

A tool that can mock out an existing Appium session, supports both Java and Kotlin.

appium-mocker A tool that can mock out an existing Appium session, supports both Java and Kotlin. How to install latest appium-mocker Beta/Snapshots

An experimental tool for building console UI in Kotlin using the Jetpack Compose compiler/runtime

An experimental tool for building console UI in Kotlin using the Jetpack Compose compiler/runtime

Utility - The cross-platform native Kotlin command line tool template

Utility The cross-platform native Kotlin command line tool template. Usage Make

Modifold - Kotlin CLI tool for moving curseforge mods to modrinth
Modifold - Kotlin CLI tool for moving curseforge mods to modrinth

Modifold Modifold is a Kotlin CLI utility that allows you to transfer mods from

The Klutter CLI tool gives access to all tasks to create and manage a Klutter project.

Klutter CLI The Klutter CLI tool gives access to all tasks to create and manage a Klutter project. Gettings started Download the tool. Unzip the file.

AndroRAT is a tool designed to give the control of the android system remotely and retrieve informations from it.
AndroRAT is a tool designed to give the control of the android system remotely and retrieve informations from it.

AndroRAT is a tool designed to give the control of the android system remotely and retrieve informations from it. Androrat is a client/server application developed in Java Android for the client side and the Server is in Python.

A powerful tool (iOS & Android) that focuses on mobile operation behavior!
A powerful tool (iOS & Android) that focuses on mobile operation behavior!

DiDiPrism,中文名:小桔棱镜,是一款专注于移动端操作行为的工具,涵盖APP操作回放、操作检测、以及数据可视化能力。我们在整个方案的实现过程中沉淀出了一套技术框架,希望可以逐步开源出来帮助更多人,同时也希望棱镜在大家的合力下能够更快的成长。 它有哪些亮点? 零入侵 业务代码无需任何适配。 高可

Comments
  • 下载成功后仍回调多次

    下载成功后仍回调多次

    // 创建任务 val downloadTask = lifecycleScope.download(downloadURL, "base.apk", this.filesDir.toString()) downloadTask.state() .onEach { state -> Log.i("Download APK", "Downloaded Progress: ${state.progress.percent()}") loadingDialog.progress = state.progress.percent().toInt() if (state is State.Succeed) { loadingDialog.dismiss() loadingDialog.progress = 0 Toast.makeText(this, "Download done!", Toast.LENGTH_LONG).show() installApk(this, ProgressDialog(this), "this.filesDir.toString()/base.apk") } } .launchIn(lifecycleScope) // 使用lifecycleScope downloadTask.start() 当本地已存在文件时下载会回调多次

    opened by flyfishxu 1
  • 下载失败

    下载失败

    单任务或者多任务下载,偶尔会卡到某个进度不再下载,点击暂停再点击继续就可以重新下载。 此外还有一个疑问请教大佬?关于状态的监听那块,具体代码如下: downloadTask.state() .onEach { state ->
    // 更新状态 setState(state) // 更新进度 setProgress(state.progress) } .launchIn(lifecycleScope) 这个状态的监听,每次recyclerview上下滑动,都会触发监听(我在这里做了本地数据库参数的初始化,通过变量控制第一次加载从本地数据库获取数据),感觉应该是DownloadTask 发送一次即可,这个地方大佬有什么好的建议吗? 感谢!

    opened by LittleSillyGirl 5
  • 下载失败

    下载失败

    依赖版本:implementation "com.github.ssseasonnn:DownloadX:1.0.2" PS:1.0.1版本也试过,也是同样的问题 使用环境:小米8,雷电模拟器,移动网,电信网 使用代码: val taskId = GlobalScope.download( "https://rls.tapimg.com/pub2/202106/cdddafbfdaea6abdf0af1e524ca568ba.apk", "taptap123.apk", getExternalFilesDir("")?.path!! // 这里不设置保存路径,使用默认路径,也会出现同样的问题 ) taskId.state(1000) .onEach { Log.w("=====", "${it.javaClass.simpleName}---${it.progress.percentStr()}") }.launchIn(lifecycleScope) taskId.start()

    异常情况:如下图(每次都是下载到某一个节点之后,就下载不动了,回调了多次同样进度之后就显示失败) image

    image

    opened by kokod21 0
Owner
Season
会写点代码
Season
🧸 A multiplatform coroutine-based wrapper for popular platform-specific Redis client libraries

?? rekt ⚠️ WARNING! This project is experimental and may be missing essential features. Please let us know if you found any issues or have any suggest

Southdust Team 3 Aug 31, 2022
Skeleton project for show the architecture of Android project using MVVM, Clean Architecture and Kotlin coroutine Flow

ClearScoreDemo Skeleton project for showing the architecture of Android project using MVVM, Clean architecture and Kotlin coroutine Flow App Architect

Plabon Modak 1 Mar 6, 2022
Android application showcasing the MVVM architecture, Clean code using Kotlin, Coroutine, Flow and databinding.

Code4Lyst Android application showcasing the MVVM architecture, Clean code using Kotlin, Coroutine, Flow and databinding. App Architecture MVVM CleanC

Plabon Modak 1 Nov 29, 2021
A Gallery app developed using kotlin and MVVM architecture with Coroutine

A Gallery app developed using kotlin and MVVM architecture Loading image from un

Atiar Talukdar 1 Dec 21, 2021
Android - kotlin Coroutine with MVVM and Paging 3

Android - kotlin Coroutine with MVVM and Paging 3 To Loarn more about paging 3 To Loarn more about LoadStateAdapter API Reference Get all items Api So

Haresh 1 Mar 17, 2022
An android open-source quick search/diff/download plugin.

Android Reference Intellij Plugin This library based on AndroidSourceViewer It's built with the Gradle and rewritten by kotlin, that's why it's a new

haoxiqiang 3 Nov 2, 2022
Kotlin coroutine capable Finite-State Machine (multiplatform)

Comachine Features Kotlin corutines. Event handlers can launch coroutines for collecting external events of performing side effects. Structured concur

Sergej Shafarenka 22 Dec 14, 2022
Kotlin coroutine capable Finite-State Machine (multiplatform)

Comachine Features Kotlin corutines. Event handlers can launch coroutines for collecting external events of performing side effects. Structured concur

Sergej Shafarenka 22 Dec 14, 2022
Kotlin Coroutine için örnek proje

Kotlin Coroutines Kotlin Coroutines: Senkron kod yazarak asenkron uygulamalar geliştirmeye yarayan bir eklentidir. Network istekleri cevap gelene kada

Murat YÜKSEKTEPE 3 Dec 7, 2022
Coroutine for Bukkit

Heartbeat Coroutines 두근두근 ❤️ 코루틴 Coroutine for Paper Features Bukkit의 mainHeartBeat(GameLoop)에서 dispatch되는 Coroutine JavaPlugin 생명주기의 CoroutineScope 유

null 22 Dec 18, 2022