Last active
October 26, 2022 11:17
-
-
Save yongjhih/e4d12dbaea5408242de6a05b85912a97 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://stackoverflow.com/questions/59103133/how-to-directly-download-a-file-to-download-directory-on-android-q-android-10