Learn to Live and Live to Learn

IT(たまにビジネス)に関する記事を読んで、考えて、使ってみたことをまとめる場。

[Android] 画像・動画ファイルをアルバムから削除する

サンプルコード

import java.io.File;
import android.content.Context;

String outputPath = <ファイルのパス>;
Context context = this;

File file = new File(outputPath);
if (file.exists()) {
    file.delete(); // ファイル自体の削除
    context.getContentResolver().delete(
        MediaStore.Files.getContentUri("external"),
        MediaStore.Files.FileColumns.DATA + "=?",
        new String[]{outputPath}
    );  // アルバムからの削除
}

説明

ContentProviderはAndroidで他アプリのDBにあるデータを操作できるコンポーネントです. このContentProviderはContentResolverインスタンスで利用できます.このインスタンスはContextクラスのgetContentResolverメソッドで取得できます. 今回はContentResolverのdelete(Uri url, String where, String[] selectionArgs)メソッドで対象の画像・動画を削除しています. MediaStore.Files.getContentUri("external")はファイル一般を全部取得できるURIです.

参考リンク