画像が勝手にギャラリーに表示される~Android のメディアスキャナーについて

Android には、アプリケーションが独自にメディアファイル(画像、動画、音楽)を管理しなくてもよいように、MediaStore が用意されており、任意のアプリケーションが MediaStore にメディアファイルを登録・参照できる。たとえば、標準アプリケーションのギャラリーは、MediaStore に登録された画像を表示している。MediaStore は非常に便利で、たとえば画像を登録すると自動的にサムネイルを作成してくれたりする。

独自にサムネイルを作成しているアプリケーションにとっては、少々やっかいな動きになる。たとえば、ギャラリーを Intent 経由で呼び出して画像をコピーした場合、同じ画像が複数 MediaStore に登録される。実際にやってみると、「元の画像」「コピーした画像」「独自に作成したサムネイル」がギャラリーに表示されるようになってしまった。ギャラリーに表示されないようにするには、MediaStore に登録するコードを書かなければいいだけだと思っていたのだが、実はそうではなく、Media Scanner がサービスとして起動しており、暇なときにメディアファイルを探して回っているらしい。

Media Scanner に、検索されないようにする方法を探してみると、MediaStore API のドキュメントにヒントがあった。

public static final String MEDIA_IGNORE_FILENAME

Added in API level 9
Name of the file signaling the media scanner to ignore media in the containing directory and its subdirectories. Developers should use this to avoid application graphics showing up in the Gallery and likewise prevent application sounds and music from showing up in the Music app.

Constant Value: “.nomedia”

さらに、.nomedia で探していくと、Storage Optionのドキュメントの中に、以下の記述があった。

Hiding your files from the Media Scanner

Include an empty file named .nomedia in your external files directory (note the dot prefix in the filename). This will prevent Android’s media scanner from reading your media files and including them in apps like Gallery or Music.

アプリケーション独自のディレクトリに、「.nomedia」ファイルを置いておけばいいってことですね。


コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

Time limit is exhausted. Please reload CAPTCHA.