728x90
안드로이드 11 아래 버전에서 아래의 코드로 사진 다운로드 할 수 있는 경로를 지정해주고 다운로드 할 수 있도록 되어 있었습니다.
Environment.getExternalStorageDirectory().absolutePath
사진에 접근하기 위한 권한으로 아래 두개도 사용하고 있었구요
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
해당 코드로 사진 다운로드 기능을 잘 사용하고 있었는데, 안드로이드 정책이 변경되면서 아래와 같은 경고를 받았습니다ㅠㅠ
'getExternalStorageDirectory(): File!' is deprecated
해결방법은 기존 코드에서 분기점을 만들어주어 Q버전 위아 아래로 나누어 작성해주면 됩니다!
fun download (urlStr: String) {
val url = URL(urlStr)
val fileName = UUID.randomUUID().toString() + ".jpg"
try {
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
try {
val fileReader = ByteArray(500000)
var fileSizeDownloaded: Long = 0
inputStream = url.openStream()
outputStream = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val resolver = atvt.contentResolver
val uri = resolver.insert(MediaStore.Files.getContentUri("external"), ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + File.separator + "test")
})
uri?.let { resolver.openOutputStream(it) }
} else {
val folderPath = Environment.getExternalStorageDirectory().absolutePath + "/test/"
val strDir = File(folderPath)
if (!strDir.exists()) {
strDir.mkdir()
}
val file = File(folderPath + fileName)
FileOutputStream(file)
}
if (outputStream != null) {
while (true) {
val read: Int? = inputStream?.read(fileReader)
if (read == -1) {
break
}
outputStream?.write(fileReader, 0, read!!)
fileSizeDownloaded += read?.toLong()!!
}
outputStream?.flush()
}
} catch (e: IOException) {
Log.d("IOException", "${e.printStackTrace()}")
} finally {
inputStream?.close()
outputStream?.close()
Log.d("SUCCESS", "다운로드 완료")
}
} catch (e: IOException) {
Log.d("IOException", "${e.printStackTrace()}")
}
}
++ 안드로이드 11에서는 android.permission.WRITE_EXTERNAL_STORAGE 획득이 없이도 저장이 가능하다고 합니다
728x90
'Kotlin' 카테고리의 다른 글
안드로이드 App Bundle API 수준 31 이상을 타겟팅해야 합니다. 해결방법 (0) | 2022.11.17 |
---|---|
안드로이드 웹뷰 카메라 & 사진 업로드 (0) | 2022.08.19 |