Hanbit the Developer

[Android] Saved image is not appearing in gallery immediately 본문

Mobile/Android

[Android] Saved image is not appearing in gallery immediately

hanbikan 2022. 11. 28. 19:45

배경

val outputStream: OutputStream = FileOutputStream(imageFile)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
outputStream.flush()
outputStream.close()

위와 같은 코드로 /Pictures/AppName 같은 루트에 이미지를 저장을 하고 갤러리 앱에 들어가보면, 저장된 사진이 그 즉시 보여지지 않습니다. 갤러리 앱에 보여지는 데 1~3분 정도가 소요되곤 하여 앱을 사용하기에 매우 불편하였습니다.

 

해결 과정

원인 및 해결책을 찾을 수 있었던 과정은 다음과 같습니다.

1. SNOW 앱은 즉시 사진이 갤러리에 보여지기 때문에, 혹시나 저장되는 위치가 잘못된 것인지 의문이 들어 SNOW가 사진을 저장하는 루트와 동일하게 사진을 저장을 해보았습니다. => 해결되지 않았습니다.

2. 갤러리 앱 뿐만 아니라 저희 앱의 ImagePicker(ContentResolver을 통해 사진을 읽어들임)에도 저장된 사진이 곧바로 보여지지 않았습니다. 여기서 힌트를 얻어, 갤러리 앱과 연관된 문제가 아니라 ContentResolver와 연관된 문제라는 것을 알 수 있었습니다.

3. 이에 따라 content resolver라는 키워드를 구글링에 사용하였고, 다음의 글을 찾을 수 있었습니다. https://stackoverflow.com/questions/38554843/contentresolver-doesnt-contain-just-created-image-in-an-immediate-query-after-c

 

ContentResolver doesn't contain just created image in an immediate query after creation of file

I'm using this code to copy an image using documentFile.createFile() private void newcopyFile(File fileInput, String outputParentPath, String mimeType, String newFileNa...

stackoverflow.com

4. 다만 글에 나와있는 솔루션이 deprecated된 내용이어서 추가로 구글링하여 해결책을 찾을 수 있었습니다.

 

해결 방법

미디어 파일을 저장한 직후, MediaScannerConnection.scanFile()이라는 정적 함수를 수행하여 해결할 수 있습니다.

// 저장한 파일을 스캔하여 해당 사진이 갤러리에서 보여지게끔 합니다.
// 아래 코드가 없을 경우, 사진을 저장하여도 곧바로 갤러리 앱에서 해당 사진을 찾아볼 수 없습니다.
MediaScannerConnection.scanFile(context, arrayOf(imageFile.path), null, null)

구글 문서는 MediaScannerConnection을 다음과 같이 설명합니다.

MediaScannerConnection provides a way for applications to pass a newly created or downloaded media file to the media scanner service. The media scanner service will read metadata from the file and add the file to the media content provider. The MediaScannerConnectionClient provides an interface for the media scanner service to return the Uri for a newly scanned file to the client of the MediaScannerConnection class.

MediaScannerConnection이 새로 생성된 미디어 파일을 Media Scanner Service에 전달하고, Media Scanner Service에서 해당 파일을 Content Provider에 추가한다고 합니다.

 

여담

매번 디렉토리들을 스캐닝하는 것이 리소스를 낭비하기 때문에 가끔 스캐닝을 수행하고, 필요한 경우 직접 스캐닝을 돌리게 한 것 같습니다.(어디서 봤는지 모르겠는데... 디바이스 리붓 등의 액션이 발생할 때 스캐닝이 수행된다고 했던 것 같아요. 이 내용은 출처가 불분명하다는 점...🧐)

 

References

https://developer.android.com/reference/android/media/MediaScannerConnection

 

MediaScannerConnection  |  Android Developers

 

developer.android.com