Android : 콘텐츠 URI에서 파일 URI를 가져 오나요?
내 앱에서 사용자는 앱이 처리 할 오디오 파일을 선택합니다. 문제는 앱이 오디오 파일로 원하는 작업을 수행하려면 URI가 파일 형식이어야한다는 것입니다. Android의 기본 음악 플레이어를 사용하여 앱에서 오디오 파일을 검색 할 때 URI는 다음과 같은 콘텐츠 URI입니다.
content://media/external/audio/media/710
그러나 널리 사용되는 파일 관리자 응용 프로그램 인 Astro를 사용하면 다음과 같은 결과가 나타납니다.
file:///sdcard/media/audio/ringtones/GetupGetOut.mp3
후자는 작업에 훨씬 더 쉽게 접근 할 수 있지만 물론 컬렉션을 탐색하는 데 사용하는 프로그램에 관계없이 사용자가 선택한 오디오 파일로 앱에 기능이 있기를 바랍니다. 제 질문은 content://스타일 URI를 URI로 변환하는 방법이 file://있습니까? 그렇지 않으면이 문제를 해결하기 위해 무엇을 권장 하시겠습니까? 다음은 참조를 위해 선택기를 호출하는 코드입니다.
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);
콘텐츠 URI로 다음을 수행합니다.
m_ringerPath = m_ringtoneUri.getPath();
File file = new File(m_ringerPath);
그런 다음 해당 파일로 FileInputStream 작업을 수행하십시오.
URI에서 getContentResolver().openInputStream(uri)가져 오기 위해 사용하십시오 InputStream.
Content Resolver를 사용 file://하여 content://URI 에서 경로 를 가져올 수 있습니다 .
String filePath = null;
Uri _uri = data.getData();
Log.d("","URI = "+ _uri);
if (_uri != null && "content".equals(_uri.getScheme())) {
Cursor cursor = this.getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(0);
cursor.close();
} else {
filePath = _uri.getPath();
}
Log.d("","Chosen path = "+ filePath);
content : // 스키마로 URI를 호출하여 처리하는 ContentResolver.query()것은 좋은 해결책이 아닙니다. 4.2.2를 실행하는 HTC Desire에서 쿼리 결과로 NULL을 얻을 수 있습니다.
대신 ContentResolver를 사용하지 않는 이유는 무엇입니까? https://stackoverflow.com/a/29141800/3205334
콘텐츠 Uri가있는 content://com.externalstorage...경우이 메서드를 사용 하여 Android 19 이상에서 폴더 또는 파일의 절대 경로를 가져올 수 있습니다 .
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
System.out.println("getPath() uri: " + uri.toString());
System.out.println("getPath() uri authority: " + uri.getAuthority());
System.out.println("getPath() uri path: " + uri.getPath());
// ExternalStorageProvider
if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
System.out.println("getPath() docId: " + docId + ", split: " + split.length + ", type: " + type);
// This is for checking Main Memory
if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
return Environment.getExternalStorageDirectory() + "/" + split[1] + "/";
} else {
return Environment.getExternalStorageDirectory() + "/";
}
// This is for checking SD Card
} else {
return "storage" + "/" + docId.replace(":", "/");
}
}
}
return null;
}
Uri의 각 부분이 println을 사용하고 있는지 확인할 수 있습니다. 내 SD 카드 및 장치 주 메모리의 반환 값은 다음과 같습니다. 파일이 메모리에 있으면 액세스하고 삭제할 수 있지만 이 방법을 사용하여 SD 카드에서 파일 을 삭제할 수 없었고이 절대 경로를 사용하여 이미지를 읽거나 열 수만 있습니다. 이 방법을 사용하여 삭제할 솔루션을 찾으면 공유하십시오. SD 카드
getPath() uri: content://com.android.externalstorage.documents/tree/612E-B7BF%3A/document/612E-B7BF%3A
getPath() uri authority: com.android.externalstorage.documents
getPath() uri path: /tree/612E-B7BF:/document/612E-B7BF:
getPath() docId: 612E-B7BF:, split: 1, type: 612E-B7BF
메인 메모리
getPath() uri: content://com.android.externalstorage.documents/tree/primary%3A/document/primary%3A
getPath() uri authority: com.android.externalstorage.documents
getPath() uri path: /tree/primary:/document/primary:
getPath() docId: primary:, split: 1, type: primary
If you wish to get Uri with file:/// after getting path use
DocumentFile documentFile = DocumentFile.fromFile(new File(path));
documentFile.getUri() // will return a Uri with file Uri
Well I am bit late to answer,but my code is tested
check scheme from uri:
byte[] videoBytes;
if (uri.getScheme().equals("content")){
InputStream iStream = context.getContentResolver().openInputStream(uri);
videoBytes = getBytes(iStream);
}else{
File file = new File(uri.getPath());
FileInputStream fileInputStream = new FileInputStream(file);
videoBytes = getBytes(fileInputStream);
}
In the above answer I converted the video uri to bytes array , but that's not related to question, I just copied my full code to show the usage of FileInputStream and InputStream as both are working same in my code.
I used the variable context which is getActivity() in my Fragment and in Activity it simply be ActivityName.this
context=getActivity(); //in Fragment
context=ActivityName.this;// in activity
참고URL : https://stackoverflow.com/questions/5657411/android-getting-a-file-uri-from-a-content-uri
'Programing' 카테고리의 다른 글
| Docker ADD 대 VOLUME (0) | 2020.08.12 |
|---|---|
| TD 내에서 위치 상대 / 절대 위치를 사용하십니까? (0) | 2020.08.12 |
| IOUtils.toString (InputStream)에 해당하는 Guava (0) | 2020.08.12 |
| Windows 용 Docker 오류 : "BIOS에서 하드웨어 지원 가상화 및 데이터 실행 보호를 활성화해야합니다." (0) | 2020.08.11 |
| 문자열이 유효한 날짜인지 확인하는 방법 (0) | 2020.08.11 |