Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Last active October 26, 2022 11:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
fun Context.outputStreamOrThrow(fileName: String, type: String = Environment.DIRECTORY_DOWNLOADS) =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
contentResolver.run {
openOutputStream(insert(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.RELATIVE_PATH, type)
}
)!!)!!
}
} else {
File(getExternalFilesDir(type)!!, fileName).outputStream()
}
fun Call.Factory.saveOrThrow(context: Context, url: HttpUrl, type: String = Environment.DIRECTORY_DOWNLOADS) =
newCall(Request.Builder().url(url).build()).execute().takeIf { it.isSuccessful }!!.body!!.byteStream().copyTo(context.outputStreamOrThrow(url.fileName(), type))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment