Skip to content

Instantly share code, notes, and snippets.

@DharmeshBasapatiBacancy
Created September 18, 2024 10:52
Show Gist options
  • Select an option

  • Save DharmeshBasapatiBacancy/2d3c1303a51ec9309697532d2b7bcdae to your computer and use it in GitHub Desktop.

Select an option

Save DharmeshBasapatiBacancy/2d3c1303a51ec9309697532d2b7bcdae to your computer and use it in GitHub Desktop.
Download any file using DownloadManager class
package com.bacancy.dispenserhmi.utils
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.util.Log
import androidx.annotation.RequiresApi
class UpdateManager(private val context: Context) {
@RequiresApi(Build.VERSION_CODES.O)
fun downloadAndInstallUpdate() {
val updateUrl = "https://github.com/markushi/android-ui/raw/master/example.apk"
// Download the APK
val request = DownloadManager.Request(Uri.parse(updateUrl))
request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, "git_apk.apk")
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadId = downloadManager.enqueue(request)
// Register a broadcast receiver to get notified when download is complete
val onComplete = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("UpdateManager", "Download complete")
val downloadedApkUri = downloadManager.getUriForDownloadedFile(downloadId)
installApk(downloadedApkUri)
}
}
context.registerReceiver(onComplete, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE),
Context.RECEIVER_NOT_EXPORTED)
}
private fun installApk(apkUri: Uri) {
Log.d("UpdateManager", "Installing APK $apkUri")
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(intent)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment