Skip to content

Commit

Permalink
Merge pull request #3 from adaptmobile-organization/feature/download-…
Browse files Browse the repository at this point in the history
…manager

remove the activity dependency when downloading files
  • Loading branch information
jasonkellydk authored Apr 10, 2019
2 parents 62a6ee7 + ed3b177 commit 2b409b6
Showing 1 changed file with 16 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package dk.adaptmobile.amkotlinutil.managers

import android.Manifest
import android.app.Activity
import android.annotation.SuppressLint
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
Expand All @@ -14,16 +14,27 @@ import androidx.annotation.RequiresPermission
/**
* @author Jason Kelly <jason@adaptagency.com>
*/
@SuppressLint("StaticFieldLeak")
object DownloadManager {
private lateinit var applicationContext: Context
private lateinit var downloadManager: DownloadManager

/**
* This will initialize the download manager with the specified
* application context
*/
fun init(context: Context) {
downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
this.applicationContext = context
}

/**
* This downloads a file using the build in download manager
* When the file is downloaded the onComplete callback will be called
* With the appropriate file URI and mimeType
*/
@RequiresPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun downloadFile(activity: Activity, url: String, downloadRequest: (DownloadManager.Request.() -> Unit)? = null, onComplete: ((uri: Uri, mimeType: String) -> Unit)? = null) {
val downloadManager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
fun downloadFile(url: String, downloadRequest: (DownloadManager.Request.() -> Unit)? = null, onComplete: ((uri: Uri, mimeType: String) -> Unit)? = null) {
val request = DownloadManager.Request(Uri.parse(url))

downloadRequest?.let { request.it() }
Expand All @@ -42,11 +53,11 @@ object DownloadManager {
onComplete?.invoke(downloadManager.getUriForDownloadedFile(downloadId), downloadManager.getMimeTypeForDownloadedFile(downloadId))

// Unregister when download finishes
activity.unregisterReceiver(this)
context?.unregisterReceiver(this)
}
}
}

activity.registerReceiver(broadcastReceiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
applicationContext.registerReceiver(broadcastReceiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
}
}

0 comments on commit 2b409b6

Please sign in to comment.