Unknown URI:content://downloads/public_downloads 해결방법

2019. 6. 13. 10:54·dev/android
728x90
반응형
SMALL

안드로이드 Unknown URI:content://downloads/public_downloads 해결 방법

 
 
 

안드로이드 이미지 파일 업로시 다운로드 관리자에서 다운로드 디렉토리에 있는 이미지 가져올떄

Unknown URI:content://downloads/public_downloads 오류가 발생하는 경우가 있다.

android 8.0 부터 content provider로 다운로드 테이블 접근시

Unknown URI: content://downloads/public_downloads 이런 오류를 발생한다.

이 방법을 해결하기 위해서 

 

선택한 이미지를 캐시디렉토리에 저장 시킨후 그 이미지 경로로 이미지를 업로드 하면 된다. 

 

String id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
    if (id.startsWith("raw:")) {
        return id.replaceFirst("raw:", "");
    }
    long fileId = getFileId(uri);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            File file = new File(context.getCacheDir().getAbsolutePath() + "/" + fileId);
            writeFile(inputStream, file);
            return file.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        String[] contentUriPrefixesToTry = new String[]{
                "content://downloads/public_downloads",
                "content://downloads/my_downloads",
                "content://downloads/all_downloads"
        };

        for (String contentUriPrefix : contentUriPrefixesToTry) {
            try {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), fileId);
                String path = getDataColumn(context, contentUri, null, null);
                if (path != null) {
                    return path;
                }
            } catch (Exception e) {
                Log.d("content-Provider", e.getMessage());
            }
        }
    }
}

 

 

private static Long getFileId(Uri uri) {
    long strReulst = 0;
    try {
        String path = uri.getPath();
        String[] paths = path.split("/");
        if (paths.length >= 3) {
            strReulst = Long.parseLong(paths[2]);
        }
    } catch (NumberFormatException | IndexOutOfBoundsException e) {
        strReulst = Long.parseLong(new File(uri.getPath()).getName());
    }
    return strReulst;
}

간혹 이미지 ID가 long 형태가 아닌 경우 위와 같이 처리 하였다.

 

private static void writeFile(InputStream in, File file) {
     OutputStream out = null;
     try {
         out = new FileOutputStream(file);
         byte[] buf = new byte[1024];
         int len;
         while ((len = in.read(buf)) > 0) {
             out.write(buf, 0, len);
         }
     } catch (Exception e) {
         e.printStackTrace();
     } finally {
         try {
             if (out != null) {
                 out.close();
             }
             in.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 }

다운로드 디렉토리에 이미지를 저장하는 부분이다. 

 

 

728x90
반응형
LIST
저작자표시 (새창열림)

'dev > android' 카테고리의 다른 글

android 키보드 보이기/숨기기  (0) 2021.01.17
Android Apache(아파치) 라이브러리 사용하기  (4) 2021.01.06
안드로이드 underline center line 적용방법  (0) 2019.01.01
안드로이드 HeadView & FooterView 커스텀 리스트뷰  (0) 2019.01.01
안드로이드 동적 마진 변경  (0) 2019.01.01
'dev/android' 카테고리의 다른 글
  • android 키보드 보이기/숨기기
  • Android Apache(아파치) 라이브러리 사용하기
  • 안드로이드 underline center line 적용방법
  • 안드로이드 HeadView & FooterView 커스텀 리스트뷰
NCJ
NCJ
일상과 개발을 공유하고 소통하는 블로그입니다.
    반응형
  • NCJ
    NCJ 프로그래밍
    NCJ
  • 전체
    오늘
    어제
    • ALL
      • dev
        • android
        • java
        • Spring Boot
        • node.js
        • MFC
        • react-native
        • web
        • 기타
        • vue
        • react
      • 일상
        • news
        • 요리
        • 영화
        • 드라마
        • 제품
        • 게임
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    갤럭시 버즈2
    코딩문제
    다이어트
    리니지w 이벤트
    리니지
    던파 사전캐릭
    던파 모바일 사전캐릭 생성
    php
    리니지W 사전예약
    갤럭시
    사전캐릭
    리니지w 보상
    CSS
    던파 모바일 서버오픈
    던파 출시일
    Web
    java
    리니지w 이벤트 안내
    Spring Boot
    갤럭시 워치 4
    apache
    리니지w
    삼성
    게임
    던파 캐릭생성
    던파 모바일 사전캐릭
    던파 서버 오픈
    리니지w 오픈
    안드로이드
    Android
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
NCJ
Unknown URI:content://downloads/public_downloads 해결방법
상단으로

티스토리툴바