회원가입∴아이디/비번찾기
홈으로


Get RealPath from Uri
10년 전
public class RealPathUtil {

    public static String getRealPath(Context context, Uri uri) {
        String realPath;
        // SDK < API11
        if (Build.VERSION.SDK_INT < 11) {
            realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(context, uri);
        }

        // SDK >= 11 && SDK < 19
        else if (Build.VERSION.SDK_INT < 19) {
            realPath = RealPathUtil.getRealPathFromURI_API11to18(context, uri);
        }

        // SDK > 19 (Android 4.4)
        else {
            realPath = RealPathUtil.getRealPathFromURI_API19(context, uri);
        }

        return realPath;
    }

    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API19(final Context context, final Uri uri) {

        // check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] { split[1] };

                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context
     *            The context.
     * @param uri
     *            The Uri to query.
     * @param selection
     *            (Optional) Filter used in the query.
     * @param selectionArgs
     *            (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }

    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        String result = null;

        CursorLoader cursorLoader = new CursorLoader(
                context,
                contentUri, proj, null, null, null);
        Cursor cursor = cursorLoader.loadInBackground();

        if(cursor != null){
            int column_index =
                    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            result = cursor.getString(column_index);
        }
        return result;
    }

    public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index
                = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
}
참고 : http://stackoverflow.com/a/28229595/3534559

추천추천 : 514 추천 목록
번호 제목
1,348
Windows 서비스 관리자에서 Apache 서버가 멈췄을 때 시스템 자체를 재부팅
1,347
윈도우에서 Apache 서버 상태를 체크한 후 문제가 발생하면 자동으로 재부팅
1,346
윈도우 서버 2019 취약점 점검 보안
1,345
윈도우 서버 2019 취약점 점검 보안 (windows server 2019)
1,344
Windows 취약점진단 보안가이드라인
1,343
Windows Admin Center를 통한 서버 관리
1,342
윈도우 서버에서 실행되는 서비스 확인
1,341
Chrome NET::ERR CERT REVOKED 해결방법
1,340
cmd 명령어 (명령 프롬프트 명령어) 모음
1,339
Windows10 특정 프로그램(OCS 2007 R2)에서 첨부파일 드래그앤드롭이 안 되는 현상
1,338
윈도우 로그, 관리 이벤트 삭제
1,337
클린 부팅
1,336
[SFC 명령어, DISM 명령어]] 무결성 검사 및 시스템 파일 손상 파일 복구
1,335
Windows Defender 검사 기록 삭제하기
1,334
간단한 윈도우 10 정품 인증 (크랙프로그램 필요없음)
1,333
오류난 폴더 강제삭제 방법
1,332
크롬에서 플래시 항상 허용하도록 설정하기 (레지스트리) reg 파일 만들기
1,331
GPT 디스크를 MBR 디스크로 변환
1,330
MBR 디스크를 GPT 디스크로 변환
1,329
구글 검색을 200% 활용하게 해주는 검색 명령어 총정리
1,328
[Jquery] jQuery로 우클릭 방지, 드래그 방지, 선택 방지 (IE10, 파이어폭스, 크롬 확인)
1,327
php 사용자 접속IP, 브라우저정보, os정보, http, https 접속프로토콜 알아오기
1,326
[PHP] IE 브라우저 접속 검출하기
1,325
윈도우10 시스템 예약 파티션 확인 및 삭제
1,324
윈도우10 복구 파티션 삭제 방법
1,323
윈도우10 부팅지연 검은화면에서 몇분간 머무는 현상 해결방법
1,322
삼성노트북 바이오스 진입이 불가능한 경우 바이오스 재설치와 NVRAM 초기화
1,321
익스플로러(IE)의 구글 검색공급자 한글로 변경 방법
1,320
윈도우 10 기본 앱 삭제 및 복구
1,319
meta 태그 http-equiv 설정방법과 차이점
목록
뮤직트로트 부산광역시 부산진구 가야동 ㅣ 개인정보취급방침ㅣ모바일버전
Copyright ⓒ musictrot All rights reserved.