본문 바로가기
dev/android

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

by NCJ 2019. 6. 13.
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