Ketch Android Library

repository·master·Indexed 20 days ago

https://github.com/khushpanchal/ketch

A Kotlin-based Android library for downloading files using WorkManager. Ketch supports pause/resume functionality, parallel downloads, and foreground service notifications to ensure downloads continue in the background. It provides Flow-based observation for tracking download progress and status, as well as utilities for managing downloads by ID or tag, validating content via HTTP headers, and customizing network behavior through a builder pattern.

Tokens
3.5K
Snippets
11
Records
15
Agent score
20%

What's inside Ketch

  1. Install Ketch via JitPack

    master

    To integrate Ketch into your Android project, add the JitPack repository to your settings.gradle file and then add the Ketch dependency to your module-level build.gradle file.

    Note: Always use the latest available version.

    // settings.gradle
    dependencyResolutionManagement {
      repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
      repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' } // add this
      }
    }
    
    // build.gradle (module level)
    dependencies {
      implementation 'com.github.khushpanchal:Ketch:2.0.6'
    }
  2. Initialize Ketch in your Application

    master

    Ketch is a singleton class. It is recommended to create the instance in your Application.onCreate() method using the Ketch.builder().

    Required Permissions: To avoid onFailure callbacks or errors, ensure you have added the following permissions to your AndroidManifest.xml:

    • INTERNET
    • WAKE_LOCK
    • FOREGROUND_SERVICE_DATA_SYNC
    • Appropriate storage permissions based on your target API level.
    • POST_NOTIFICATIONS (Required for Android 13+ if using notifications).
    private lateinit var ketch: Ketch
    
    override fun onCreate() {
      super.onCreate()
      ketch = Ketch.builder().build(this)
    }
  3. Customize Ketch configuration

    master

    You can customize the network behavior, timeouts, and the underlying HTTP client during initialization using the Ketch.builder().

    // Custom Timeouts
    ketch = Ketch.builder().setDownloadConfig(
        config = DownloadConfig(
            connectTimeOutInMs = 20000L,
            readTimeOutInMs = 15000L
        )
    ).build(this)
    
    // Custom OkHttp Client
    ketch = Ketch.builder().setOkHttpClient(
        okHttpClient = OkHttpClient.Builder()
            .connectTimeout(10000L)
            .readTimeout(10000L)
            .build()
    ).build(this)
    
    // Custom Notification Details
    ketch = Ketch.builder().setNotificationConfig(
        config = NotificationConfig(
            enabled = true,
            channelName = "My Channel",
            channelDescription = "My Description",
            importance = NotificationManager.IMPORTANCE_HIGH,
            smallIcon = R.drawable.ic_notification,
            showSpeed = true,
            showSize = true,
            showTime = true
        )
    ).build(this)
  4. Configure Notifications

    master

    To enable download notifications, you must first add the POST_NOTIFICATIONS permission to your manifest and request it from the user at runtime (for Android 13+). Then, configure the NotificationConfig during Ketch initialization.

    Note: smallIcon is a required parameter.

    // 1. Manifest
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    
    // 2. Initialization
    ketch = Ketch.builder().setNotificationConfig(
        config = NotificationConfig(
            enabled = true,
            smallIcon = R.drawable.ic_launcher_foreground
        )
    ).build(this)
  5. How download statuses work

    master

    A download follows a specific lifecycle of states:

    1. Status.QUEUED: The download is waiting to start.
    2. Status.STARTED: The download has begun.
    3. Status.PROGRESS: The download is actively transferring data.

    Terminating States:

    • Status.SUCCESS: Download completed successfully.
    • Status.PAUSED: Download was manually paused.
    • Status.CANCELLED: Download was cancelled by the user.
    • Status.FAILED: Download failed due to an error.
  6. Initialize Ketch using the Builder

    master

    Ketch is a singleton class. You should initialize it once, typically in your Application class, using the Ketch.builder() pattern. You can configure download settings, notifications, logging, and a custom OkHttpClient during initialization.

    Note: If you provide a custom OkHttpClient via setOkHttpClient(), the DownloadConfig timeout values will be ignored as the library will use the timeouts defined in your provided client.

    // Simplest way to initialize:
    Ketch.builder().build(context)
    
    // Comprehensive initialization in Application class:
    class MainApplication : Application() {
        lateinit var ketch: Ketch
    
        override fun onCreate() {
            super.onCreate()
            ketch = Ketch.builder()
                .setOkHttpClient(myCustomOkHttpClient) // optional
                .setDownloadConfig(DownloadConfig()) // optional
                .setNotificationConfig(
                    NotificationConfig(
                        true, // enabled
                        smallIcon = R.drawable.ic_launcher_foreground
                    )
                ) // optional
                .enableLogs(true) // optional
                .setLogger(myCustomLogger) // optional
                .build(this)
        }
    }
  7. Delete download records and files

    master

    Use clearDb to remove download entries from the internal database. You can choose whether or not to also delete the actual file from storage.

    // Removes entry from DB and deletes the actual file
    ketch.clearDb(downloadModel.id)
    
    // Removes entry from DB but SKIPS actual file deletion
    ketch.clearDb(downloadModel.id, false)
    
    // Other options
    ketch.clearAllDb()
    ketch.clearDb(tag)
    ketch.clearDb(timeInMillis)
  8. Manage downloads: Pause, Resume, Cancel, and Retry

    master

    Ketch provides methods to control active or paused downloads using their unique id or a custom tag assigned during the download request.

    // Using ID
    ketch.cancel(downloadModel.id)
    ketch.pause(downloadModel.id)
    ketch.resume(downloadModel.id)
    ketch.retry(downloadModel.id)
    
    // Using Tag
    ketch.cancel(tag)
    ketch.pause(tag)
    ketch.resume(tag)
    ketch.retry(tag)
    
    // Bulk operations
    ketch.cancelAll()
    ketch.pauseAll()
    ketch.resumeAll()
    ketch.retryAll()
  9. Add headers and tags to downloads

    master

    When calling download(), you can provide custom HTTP headers and a tag. Tags are useful for grouping multiple downloads together so they can be paused, resumed, or cancelled as a single group.

    ketch.download(
        url = url,
        fileName = fileName,
        path = path,
        headers = mapOf("Authorization" to "Bearer token"), // Default: empty map
        tag = "my_group_tag" // Default: null
    )
  10. Observe all download items

    master

    To monitor all ongoing or completed downloads in your application (e.g., to populate a list in a Fragment), use ketch.observeDownloads() which returns a Flow of all download items.

    // Inside a Fragment
    viewLifecycleOwner.lifecycleScope.launch {
      repeatOnLifecycle(Lifecycle.State.STARTED) {
        ketch.observeDownloads()
          .flowOn(Dispatchers.IO)
          .collect { items -> 
             // items is a list of download models to set to your adapter
          }
      }
    }
  11. Download a file and observe its status

    master

    Use ketch.download(url, fileName, path) to start a download. It returns a unique id which you can use to observe the specific download's progress and metadata via a Kotlin Flow.

    val id = ketch.download(url, fileName, path)
    
    lifecycleScope.launch {
      repeatOnLifecycle(Lifecycle.State.STARTED) {
        ketch.observeDownloadById(id)
          .flowOn(Dispatchers.IO)
          .collect { downloadModel -> 
            // downloadModel contains: url, fileName, path, tag, id, 
            // status, progress, length, speed, etc.
          }
      }
    }
  12. Control and manage downloads by ID or Tag

    master

    Once you have a download ID or have assigned a tag to your downloads, you can manage their lifecycle using the following methods:

    ActionBy IDBy TagAll
    Pausepause(id)pause(tag)pauseAll()
    Resumeresume(id)resume(tag)resumeAll()
    Retryretry(id)retry(tag)retryAll()
    Cancelcancel(id)cancel(tag)cancelAll()

    Additionally, you can clear database entries and files:

    • clearDb(id, deleteFile = true): Clears a specific download.
    • clearDb(tag, deleteFile = true): Clears all downloads with a specific tag.
    • clearDb(timeInMillis, deleteFile = true): Clears downloads older than the timestamp.
    • clearAllDb(deleteFile = true): Wipes all download data and files.