Ketch es una biblioteca de descarga de archivos para Android sencilla, potente y personalizable construida íntegramente en Kotlin. Simplifica el proceso de descarga de archivos en aplicaciones de Android aprovechando el poder de WorkManager. Ketch garantiza la descarga independientemente del estado de la aplicación.
Para integrar la biblioteca Ketch en su proyecto de Android, siga estos sencillos pasos:
dependencyResolutionManagement {
repositoriesMode . set( RepositoriesMode . FAIL_ON_PROJECT_REPOS )
repositories {
google()
mavenCentral()
maven { url ' https://jitpack.io ' } // this one
}
}
dependencies {
implementation ' com.github.khushpanchal:Ketch:2.0.2 ' // Use latest available version
}
La forma más sencilla de utilizar Ketch:
Cree la instancia de Ketch en la aplicación onCreate. (Ketch es una clase singleton y la instancia se creará automáticamente en el primer uso)
private lateinit var ketch : Ketch
override fun onCreate () {
super .onCreate()
ketch = Ketch .builder().build( this )
}
Llame a la función download(), pase la URL, el nombre del archivo, la ruta y observe el estado de la descarga.
val id = ketch.download(url, fileName, path)
lifecycleScope.launch {
repeatOnLifecycle( Lifecycle . State . STARTED ) {
ketch.observeDownloadById(id)
.flowOn( Dispatchers . IO )
.collect { downloadModel ->
// use downloadModel
}
}
}
Para cancelar la descarga
ketch.cancel(downloadModel.id) // other options: cancel(tag), cancelAll()
Para pausar la descarga
ketch.pause(downloadModel.id) // other options: pause(tag), pauseAll()
Para reanudar la descarga
ketch.resume(downloadModel.id) // other options: resume(tag), resumeAll()
Para volver a intentar la descarga
ketch.retry(downloadModel.id) // other options: retry(tag), retryAll()
Para eliminar la descarga
ketch.clearDb(downloadModel.id) // other options: clearDb(tag), clearAllDb(), clearDb(timeInMillis)
ketch.clearDb(downloadModel.id, false ) // Pass "false" to skip the actual file deletion (only clear entry from DB)
Observación: proporciona el flujo de estado de los elementos de descarga (cada elemento contiene información de descarga como URL, nombre de archivo, ruta, etiqueta, identificación, tiempo de cola, estado, progreso, longitud, velocidad, última modificación, metadatos, motivo de falla, etiqueta electrónica)
// To observe from Fragment
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle( Lifecycle . State . STARTED ) {
ketch.observeDownloads()
.flowOn( Dispatchers . IO )
.collect {
// set items to adapter
}
}
}
Para habilitar la notificación:
Agregue el permiso de notificación en el archivo de manifiesto.
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
Solicitar permiso al usuario (requerido a partir de Android 13 (nivel de API 33)). Consulte la aplicación de muestra como referencia.
Pase la configuración de notificación durante la inicialización
ketch = Ketch .builder().setNotificationConfig(
config = NotificationConfig (
enabled = true ,
smallIcon = R .drawable.ic_launcher_foreground // It is required to pass the smallIcon for notification.
)
).build( this )
Proporcione encabezados con la solicitud de red.
ketch.download(url, fileName, path,
headers = headers, // Default: Empty hashmap
)
Etiqueta: agrupe varias descargas proporcionando una etiqueta adicional. (Esta etiqueta también se puede utilizar para cancelar, pausar, reanudar y eliminar la descarga)
ketch.download(url, fileName, path,
tag = tag, // Default: null
)
Descargar configuración: proporciona conexión personalizada y tiempo de espera de lectura
ketch = Ketch .builder().setDownloadConfig(
config = DownloadConfig (
connectTimeOutInMs = 20000L , // Default: 10000L
readTimeOutInMs = 15000L // Default: 10000L
)
).build( this )
OKHttp personalizado: proporciona un cliente okhttp personalizado
ketch = Ketch .builder().setOkHttpClient(
okHttpClient = OkHttpClient
. Builder ()
.connectTimeout( 10000L )
.readTimeout( 10000L )
.build()
).build( this )
Configuración de notificación: proporcionar configuración de notificación personalizada
ketch = Ketch .builder().setNotificationConfig(
config = NotificationConfig (
enabled = true , // Default: false
channelName = channelName, // Default: "File Download"
channelDescription = channelDescription, // Default: "Notify file download status"
importance = importance, // Default: NotificationManager.IMPORTANCE_HIGH
smallIcon = smallIcon, // It is required
showSpeed = true , // Default: true
showSize = true , // Default: true
showTime = true // Default: true
)
).build( this )
Consulte el blog para comprender el funcionamiento de Ketch (diseño de alto nivel): https://medium.com/@khush.panchal123/ketch-android-file-downloader-library-7369f7b93bd1
No dude en enviar comentarios, informar un problema o contribuir a Ketch. Dirígete al repositorio de GitHub, crea un problema o busca el problema pendiente. ¿Todas las solicitudes de extracción son bienvenidas?
Copyright (C) 2024 Khush Panchal
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.