Skip to main content

How to cancel a download using DownloadManager in Kotlin Android

How to cancel a download using DownloadManager in Kotlin Android.

Here's a step-by-step tutorial on how to cancel a download using DownloadManager in Kotlin for Android:

Step 1: Set up the project

  • Create a new Android project in Kotlin.
  • Open the app-level build.gradle file and add the following dependency:
    implementation 'androidx.core:core-ktx:1.5.0'
  • Sync the project to download the dependency.

Step 2: Create layout file

  • Open the activity_main.xml layout file.
  • Add a Button with the text "Start Download".
  • Add another Button with the text "Cancel Download".
  • Assign appropriate IDs to both buttons.

Step 3: Implement the download functionality

  • Open the MainActivity.kt file.

  • Import the required classes:

    import android.app.DownloadManager
    import android.content.Context
    import android.net.Uri
    import android.os.Bundle
    import android.view.View
    import androidx.appcompat.app.AppCompatActivity
  • Declare the variables:

    private lateinit var downloadManager: DownloadManager
    private var downloadId: Long = 0
  • Initialize the downloadManager in the onCreate() method:

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    }
  • Implement the click listener for the "Start Download" button:

    fun startDownload(view: View) {
    val request = DownloadManager.Request(Uri.parse("URL_OF_FILE_TO_DOWNLOAD"))
    .setTitle("My File")
    .setDescription("Downloading")
    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)

    downloadId = downloadManager.enqueue(request)
    }
  • Implement the click listener for the "Cancel Download" button:

    fun cancelDownload(view: View) {
    downloadManager.remove(downloadId)
    }

That's it! You have successfully implemented the functionality to start and cancel a download using DownloadManager in Kotlin for Android.