본문 바로가기

Android

Android 이미지(파일) 다운로드 및 갤러리 추가

기존에는 Stream을 통한 파일 다운로드를 주로 작성을 했는데, 정책이 업데이트되면서 공용 외부 폴더에 접근이 불가능해지고 애를 먹었는데, 다운로드 매니저를 사용하는 경우 공용 폴더에도 접근이 가능하고 따로 스캔 처리를 해주지 않아도 이미지가 갤러리에 인식이 되어서 추가로 별다른 처리를 하지 않아도 됐습니다.  

try{
    final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri downloadUri = Uri.parse({fileUrl});
    DownloadManager.Request request = new DownloadManager.Request(downloadUri);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false)
            .setTitle({fileName} + "." + {fileExtension})
            .setMimeType({fileType} + {fileExtension}) // Your file type. You can use this code to download other file types also.
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,File.separator + {yourFolder} + File.separator + {fileName} + "." + {fileExtension});
    dm.enqueue(request);
}catch (Exception e){
    e.printStackTrace();
}