티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Android: Getting a file URI from a content URI?
Android: 콘텐트 URI에서 파일 URI 가져오기?
문제 내용
In my app the user is to select an audio file which the app then handles. The problem is that in order for the app to do what I want it to do with the audio files, I need the URI to be in file format. When I use Android's native music player to browse for the audio file in the app, the URI is a content URI, which looks like this:
제 앱에서 사용자는 앱에서 처리할 오디오 파일을 선택합니다. 문제는 앱이 오디오 파일로 원하는 대로 작동하려면 URI가 파일 형식이어야 한다는 것입니다. Android의 기본 음악 플레이어를 사용하여 앱에서 오디오 파일을 찾으려고하면 URI는 다음과 같은 콘텐트 URI입니다.
content://media/external/audio/media/710
However, using the popular file manager application Astro, I get the following:
그러나 인기있는 파일 관리자 응용 프로그램 Astro를 사용하면 다음과 같은 결과를 얻습니다.
file:///sdcard/media/audio/ringtones/GetupGetOut.mp3
The latter is much more accessible for me to work with, but of course I want the app to have functionality with the audio file the user chooses regardless of the program they use to browse their collection. So my question is, is there a way to convert the content://
style URI into a file://
URI? Otherwise, what would you recommend for me to solve this problem? Here is the code which calls up the chooser, for reference:
후자가 더 사용하기 쉬우며 작업할 수 있지만, 사용자가 컬렉션을 탐색하는 데 사용하는 프로그램에 관계없이 사용자가 선택한 오디오 파일이 앱과 기능을 공유하도록하려면 어떻게해야 할까요? 그렇다면 콘텐트 : // 스타일 URI를 파일 : // URI로 변환하는 방법이 있습니까? 그렇지 않으면이 문제를 해결하기 위해 무엇을 권장하시겠습니까? 참조 용으로 선택기를 호출하는 코드는 다음과 같습니다.
Intent ringIntent = new Intent();
ringIntent.setType("audio/mp3");
ringIntent.setAction(Intent.ACTION_GET_CONTENT);
ringIntent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(ringIntent, "Select Ringtone"), SELECT_RINGTONE);
I do the following with the content URI:
콘텐트 URI로 다음과 같이 수행합니다.
m_ringerPath = m_ringtoneUri.getPath();
File file = new File(m_ringerPath);
Then do some FileInputStream stuff with said file.
그런 다음 해당 파일과 FileInputStream 작업을 수행합니다.
높은 점수를 받은 Solution
Just use getContentResolver().openInputStream(uri)
to get an InputStream
from a URI.
단순히 getContentResolver().openInputStream(uri)를 사용하여 URI에서 InputStream을 가져옵니다.
가장 최근 달린 Solution
Try this....
다음을 시도해보세요.
get File from a content uri
콘텐트 uri에서 파일 가져 오기
fun fileFromContentUri(context: Context, contentUri: Uri): File {
// Preparing Temp file name
val fileExtension = getFileExtension(context, contentUri)
val fileName = "temp_file" + if (fileExtension != null) ".$fileExtension" else ""
// Creating Temp file
val tempFile = File(context.cacheDir, fileName)
tempFile.createNewFile()
try {
val oStream = FileOutputStream(tempFile)
val inputStream = context.contentResolver.openInputStream(contentUri)
inputStream?.let {
copy(inputStream, oStream)
}
oStream.flush()
} catch (e: Exception) {
e.printStackTrace()
}
return tempFile
}
private fun getFileExtension(context: Context, uri: Uri): String? {
val fileType: String? = context.contentResolver.getType(uri)
return MimeTypeMap.getSingleton().getExtensionFromMimeType(fileType)
}
@Throws(IOException::class)
private fun copy(source: InputStream, target: OutputStream) {
val buf = ByteArray(8192)
var length: Int
while (source.read(buf).also { length = it } > 0) {
target.write(buf, 0, length)
}
}
출처 : https://stackoverflow.com/questions/5657411/android-getting-a-file-uri-from-a-content-uri
'개발 > 안드로이드' 카테고리의 다른 글
RecyclerView에서 특정 위치에 있는 뷰 가져오기 (0) | 2023.02.12 |
---|---|
안드로이드 ScrollView에서 스크롤 바 트랙 제거하기 (0) | 2023.02.12 |
알림 클릭: 활동이 이미 열려 있습니다 (0) | 2023.02.11 |
fragment에서 startActivityForResult()를 실행하고 결과 받기 (0) | 2023.02.11 |
모바일 웹사이트 입력창에 포커스가 갈 때 숫자 키패드가 나오게 하기 (0) | 2023.02.10 |