Skip to content

Instantly share code, notes, and snippets.

@abhimuktheeswarar
Last active September 15, 2021 09:57
Show Gist options
  • Save abhimuktheeswarar/a8c59f825c714652ee44ba5236c35ed8 to your computer and use it in GitHub Desktop.
Save abhimuktheeswarar/a8c59f825c714652ee44ba5236c35ed8 to your computer and use it in GitHub Desktop.
Code snippet for downloading and opening a PDF file
class DownloadAndOpenPdf(
private val applicationContext: Context,
private val okHttpClient: OkHttpClient,
private val scope: CoroutineScope
) {
private val tag = "DownloadAndOpenPdf"
private var inProgress: Boolean = false
private lateinit var file: File
@Suppress("BlockingMethodInNonBlockingContext")
private fun download(id: String) =
scope.launch(Dispatchers.IO + CoroutineExceptionHandler { _, throwable ->
throwable.printStackTrace()
inProgress = false
}) {
val url = "https://msa.com/${id}/xxx"
val request = Request.Builder().url(url).build()
val response = okHttpClient.newCall(request).execute()
val body = response.body
val responseCode = response.code
if (responseCode >= HttpURLConnection.HTTP_OK && responseCode < HttpURLConnection.HTTP_MULT_CHOICE && body != null) {
val fileName = "${id}.pdf"
if (::file.isInitialized && file.exists()) {
file.delete()
}
file = File(applicationContext.cacheDir, fileName)
body.byteStream().apply {
file.outputStream().use { fileOut ->
copyTo(fileOut)
}
}
val contentUri = FileProvider.getUriForFile(
applicationContext, applicationContext.packageName, file
)
openPdfFile(contentUri)
} else {
Log.e(tag, "Error downloading")
}
inProgress = false
}
private fun delete() {
try {
if (::file.isInitialized && file.exists()) {
file.delete()
//Alternate: Android 22 & above
//applicationContext.contentResolver.delete(uri, null)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun deleteFromWorker() {
val fileName = inputData.getString("fileName") ?: return Result.failure()
val file = File(appContext.cacheDir, fileName)
val isDeleted = if (file.exists()) {
file.delete()
} else true
}
companion object {
private fun openPdfFile(uri: Uri, activity: AppCompatActivity) = with(activity) {
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_GRANT_READ_URI_PERMISSION
intent.setDataAndType(uri, contentResolver.getType(uri))
startActivity(intent)
}
private fun sharePdfFile(uri: Uri, activity: AppCompatActivity) = with(activity) {
val intent = Intent()
intent.action = Intent.ACTION_SEND
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
intent.type = contentResolver.getType(uri)
intent.putExtra(Intent.EXTRA_STREAM, uri)
startActivity(intent)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment