多くのアプリは、充実したユーザー エクスペリエンスを提供するために、外部ストレージ ボリュームで利用可能なメディアにユーザーがアクセスしてデータを書き込む機能を備えています。フレームワークでは、「メディアストア」と呼ばれるメディア コレクションに対して、最適化されたインデックスが提供されます。これにより、メディア ファイルの取得と更新がより簡単になります。アプリがアンインストールされても、この種のファイルはユーザーのデバイスに残ります。
メディアストアを抽象化して操作するには、アプリのコンテキストから取得した ContentResolver
オブジェクトを使用します。
Kotlin
val projection = arrayOf(media-database-columns-to-retrieve) val selection = sql-where-clause-with-placeholder-variables val selectionArgs = values-of-placeholder-variables val sortOrder = sql-order-by-clause applicationContext.contentResolver.query( MediaStore.media-type.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder )?.use { cursor -> while (cursor.moveToNext()) { // Use an ID column from the projection to get // a URI representing the media item itself. } }
Java
String[] projection = new String[] { media-database-columns-to-retrieve }; String selection = sql-where-clause-with-placeholder-variables; String[] selectionArgs = new String[] { values-of-placeholder-variables }; String sortOrder = sql-order-by-clause; Cursor cursor = getApplicationContext().getContentResolver().query( MediaStore.media-type.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder ); while (cursor.moveToNext()) { // Use an ID column from the projection to get // a URI representing the media item itself. }
システムは、外部ストレージ ボリュームを自動的にスキャンし、メディア ファイルを以下の明確に定義されたコレクションに追加します。
- 画像(写真とスクリーンショットを含む)は、
DCIM/
ディレクトリとPictures/
ディレクトリに格納されます。システムは、この種のファイルをMediaStore.Images
テーブルに追加します。 - 動画は
DCIM/
、Movies/
、Pictures/
ディレクトリに格納されます。システムは、この種のファイルをMediaStore.Video
テーブルに追加します。 - オーディオ ファイルは
Alarms/
、Audiobooks/
、Music/
、Notifications/
、Podcasts/
、Ringtones/
ディレクトリに格納されます。また、オーディオ プレイリストはMusic/
ディレクトリまたはMovies/
ディレクトリに格納されます。システムは、この種のファイルをMediaStore.Audio
テーブルに追加します。 - ダウンロードされたファイルは
Download/
ディレクトリに格納されます。Android 10(API レベル 29)以上を実行しているデバイスでは、この種のファイルはMediaStore.Downloads
テーブルに格納されます。このテーブルは、Android 9(API レベル 28)以下では使用できません。
メディアストアには、MediaStore.Files
という名前のコレクションも含まれています。Android 10 以上をターゲットとするアプリで利用可能な対象範囲別ストレージをアプリが使用しているかどうかによって、コレクションのコンテンツは異なります。
- 対象範囲別ストレージが有効になっている場合、このコレクションは、アプリが作成した写真、動画、オーディオ ファイルのみを表示します。
- 対象範囲別ストレージが使用できない場合または使用されていない場合、このコレクションはすべてのタイプのメディア ファイルを表示します。
必要な権限をリクエストする
メディア ファイルに対するオペレーションを実行する前に、アプリがメディア ファイルにアクセスするために必要な権限を宣言していることを確認します。ただし、必要のない権限または使用しない権限をアプリで宣言すべきではないことに留意してください。
ストレージに関する権限
アプリでメディア ファイルにアクセスするための権限モデルは、Android 10 以上をターゲットとするアプリで利用可能な対象範囲別ストレージをアプリが使用しているかどうかによって異なります。
対象範囲別ストレージが有効になっている場合
アプリが対象範囲別ストレージを使用している場合、Android 9(API レベル 28)以下を実行しているデバイスでのみ、ストレージ関連の権限をリクエストする必要があります。この条件を適用するには、アプリのマニフェスト ファイルで権限の宣言に android:maxSdkVersion
属性を追加します。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
Android 10 以上を実行しているデバイスでは、必要のないストレージ関連の権限をリクエストしないでください。ストレージ関連の権限をリクエストしなくても、アプリは、MediaStore.Downloads
コレクションを含む明確に定義されたメディア コレクションにデータを書き込むことができます。たとえば、カメラアプリを開発する場合、ストレージ関連の権限をリクエストする必要はありません。メディアストアに書き込む画像をアプリが所有しているからです。
他のアプリが作成したファイルにアクセスする場合は、以下の条件をすべて満たす必要があります。
- アプリに
READ_EXTERNAL_STORAGE
権限が付与されている。 - 該当ファイルが、以下の明確に定義されたメディア コレクションのいずれかに含まれている。
特に、アプリが作成していない MediaStore.Downloads
コレクション内のファイルにアクセスする場合は、ストレージ アクセス フレームワークを使用する必要があります。このフレームワークの使用方法の詳細については、ドキュメントとその他のファイルにアクセスする方法のガイドをご覧ください。
対象範囲別ストレージを使用しない場合
Android 9 以下を実行しているデバイスでアプリが使用される場合、またはアプリがストレージ互換性機能を使用している場合は、メディア ファイルにアクセスするための READ_EXTERNAL_STORAGE
権限をリクエストする必要があります。メディア ファイルを変更したい場合は、WRITE_EXTERNAL_STORAGE
権限もリクエストする必要があります。
メディアの位置情報に関する権限
アプリが対象範囲別ストレージを使用している場合、写真から無編集の EXIF メタデータを取得するには、アプリのマニフェストで ACCESS_MEDIA_LOCATION
権限を宣言し、実行時にこの権限をリクエストします。
メディア コレクションをクエリする
特定の条件(「再生時間が 5 分以上」など)を満たすメディアを検索するには、次のコード スニペットに示すように、SQL に似た選択ステートメントを使用します。
Kotlin
// Need the READ_EXTERNAL_STORAGE permission if accessing video files that your // app didn't create. // Container for information about each video. data class Video(val uri: Uri, val name: String, val duration: Int, val size: Int ) val videoList = mutableListOf<Video>() val projection = arrayOf( MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DURATION, MediaStore.Video.Media.SIZE ) // Show only videos that are at least 5 minutes in duration. val selection = "${MediaStore.Video.Media.DURATION} >= ?" val selectionArgs = arrayOf( TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES).toString() ) // Display videos in alphabetical order based on their display name. val sortOrder = "${MediaStore.Video.Media.DISPLAY_NAME} ASC" val query = ContentResolver.query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder ) query?.use { cursor -> // Cache column indices. val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID) val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME) val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION) val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE) while (cursor.moveToNext()) { // Get values of columns for a given video. val id = cursor.getLong(idColumn) val name = cursor.getString(nameColumn) val duration = cursor.getInt(durationColumn) val size = cursor.getInt(sizeColumn) val contentUri: Uri = ContentUris.withAppendedId( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id ) // Stores column values and the contentUri in a local object // that represents the media file. videoList += Video(contentUri, name, duration, size) } }
Java
// Need the READ_EXTERNAL_STORAGE permission if accessing video files that your // app didn't create. // Container for information about each video. class Video { private final Uri uri; private final String name; private final int duration; private final int size; public Video(Uri uri, String name, int duration, int size) { this.uri = uri; this.name = name; this.duration = duration; this.size = size; } } List<Video> videoList = new ArrayList<Video>(); String[] projection = new String[] { MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DURATION, MediaStore.Video.Media.SIZE }; String selection = MediaStore.Video.Media.DURATION + " >= ?"; String[] selectionArgs = new String[] { String.valueOf(TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES)); }; String sortOrder = MediaStore.Video.Media.DISPLAY_NAME + " ASC"; try (Cursor cursor = getApplicationContext().getContentResolver().query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder )) { // Cache column indices. int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID); int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME); int durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION); int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE); while (cursor.moveToNext()) { // Get values of columns for a given video. long id = cursor.getLong(idColumn); String name = cursor.getString(nameColumn); int duration = cursor.getInt(durationColumn); int size = cursor.getInt(sizeColumn); Uri contentUri = ContentUris.withAppendedId( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id); // Stores column values and the contentUri in a local object // that represents the media file. videoList.add(new Video(contentUri, name, duration, size)); } }
アプリでこのようなクエリを実行する場合は、次の点に留意してください。
- ワーカー スレッドで
query()
メソッドを呼び出します。 - クエリ結果の行を処理するたびに
getColumnIndexOrThrow()
を呼び出す必要をなくすため、列インデックスをキャッシュに保存します。 - コード スニペットに示すように、コンテンツ URI の末尾に ID を付加します。
- Android 10 以上を実行しているデバイスでは、
MediaStore
API で定義された列名が必要です。アプリ内の依存元ライブラリが想定している列名("MimeType"
など)が API で定義されていない場合は、CursorWrapper
を使用して、アプリのプロセス内で列名を動的に変換します。
ファイルのサムネイルを読み込む
複数のメディア ファイルを表示するアプリでファイルの選択をユーザーにリクエストする場合は、ファイル自体を読み込むより、ファイルのプレビュー バージョン(サムネイル)を読み込むほうが効率的です。
特定のメディア ファイルのサムネイルを読み込むには、読み込みたいサムネイルのサイズを渡して loadThumbnail()
を使用します。次のコード スニペットをご覧ください。
Kotlin
// Load thumbnail of a specific media item. val thumbnail: Bitmap = applicationContext.contentResolver.loadThumbnail( content-uri, Size(640, 480), null)
Java
// Load thumbnail of a specific media item. Bitmap thumbnail = getApplicationContext().getContentResolver().loadThumbnail( content-uri, new Size(640, 480), null);
メディア ファイルを開く
メディア ファイルを開くために使用する具体的なロジックは、メディア コンテンツをファイル記述子とファイル ストリームのどちらで表現するのが適切かによって決まります。
ファイル記述子
ファイル記述子を使用してメディア ファイルを開くには、次のコード スニペットに示すようなロジックを使用します。
Kotlin
// Open a specific media item using ParcelFileDescriptor. val resolver = applicationContext.contentResolver // "rw" for read-and-write; // "rwt" for truncating or overwriting existing file contents. val readOnlyMode = "r" resolver.openFileDescriptor(content-uri, readOnlyMode).use { pfd -> // Perform operations on "pfd". }
Java
// Open a specific media item using ParcelFileDescriptor. ContentResolver resolver = getApplicationContext() .getContentResolver(); // "rw" for read-and-write; // "rwt" for truncating or overwriting existing file contents. String readOnlyMode = "r"; try (ParcelFileDescriptor pfd = resolver.openFileDescriptor(content-uri, readOnlyMode)) { // Perform operations on "pfd". } catch (IOException e) { e.printStackTrace(); }
ファイル ストリーム
ファイル ストリームを使用してメディア ファイルを開くには、次のコード スニペットに示すようなロジックを使用します。
Kotlin
// Open a specific media item using InputStream. val resolver = applicationContext.contentResolver resolver.openInputStream(content-uri).use { stream -> // Perform operations on "stream". }
Java
// Open a specific media item using InputStream. ContentResolver resolver = getApplicationContext() .getContentResolver(); try (InputStream stream = resolver.openInputStream(content-uri)) { // Perform operations on "stream". }
メディア コンテンツにアクセスする際の考慮事項
メディア コンテンツにアクセスする際は、以下のセクションで説明する考慮事項に留意してください。
ストレージ ボリューム
Android 10 以上をターゲットとするアプリは、システムが外部ストレージ ボリュームごとに割り当てる一意の名前にアクセスできます。この命名システムは、コンテンツを効率的に整理してインデックスを付け、新しいメディア ファイルの保存場所を管理するのに役立ちます。
プライマリ共有ストレージ ボリュームの名前は、常に VOLUME_EXTERNAL_PRIMARY
です。その他のボリュームを見つけるには、次のように MediaStore.getExternalVolumeNames()
を呼び出します。
Kotlin
val volumeNames: Set<String> = MediaStore.getExternalVolumeNames(context) val firstVolumeName = volumeNames.iterator().next()
Java
Set<String> volumeNames = MediaStore.getExternalVolumeNames(context); String firstVolumeName = volumeNames.iterator().next();
写真の位置情報
写真によっては、EXIF メタデータ内に位置情報が含まれていて、写真の撮影場所をユーザーが確認できる場合があります。しかし、この位置情報は機密情報であるため、Android 10 では、対象範囲別ストレージを使用しているアプリに対してはデフォルトで非表示になっています。
アプリが写真の位置情報にアクセスする必要がある場合は、次の手順を実施します。
- アプリのマニフェストで
ACCESS_MEDIA_LOCATION
権限をリクエストします。 MediaStore
オブジェクトから、setRequireOriginal()
を呼び出して写真の URI を渡すことにより、写真の正確なバイトを取得します。次のコード スニペットをご覧ください。Kotlin
val photoUri: Uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cursor.getString(idColumnIndex) ) // Get location data using the Exifinterface library. // Exception occurs if ACCESS_MEDIA_LOCATION permission isn't granted. photoUri = MediaStore.setRequireOriginal(photoUri) contentResolver.openInputStream(photoUri)?.use { stream -> ExifInterface(stream).run { // If lat/long is null, fall back to the coordinates (0, 0). val latLong = latLong ?: doubleArrayOf(0.0, 0.0) } }
Java
Uri photoUri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cursor.getString(idColumnIndex)); final double[] latLong; // Get location data using the Exifinterface library. // Exception occurs if ACCESS_MEDIA_LOCATION permission isn't granted. photoUri = MediaStore.setRequireOriginal(photoUri); InputStream stream = getContentResolver().openInputStream(photoUri); if (stream != null) { ExifInterface exifInterface = new ExifInterface(stream); double[] returnedLatLong = exifInterface.getLatLong(); // If lat/long is null, fall back to the coordinates (0, 0). latLong = returnedLatLong != null ? returnedLatLong : new double[2]; // Don't reuse the stream associated with // the instance of "ExifInterface". stream.close(); } else { // Failed to load the stream, so return the coordinates (0, 0). latLong = new double[2]; }
メディアの共有
一部のアプリでは、ユーザーはメディア ファイルを互いに共有できます。たとえば、ソーシャル メディア アプリでは、写真や動画を友だちと共有できます。
メディア ファイルを共有するには、コンテンツ プロバイダの作成ガイドで推奨されているように、content://
URI を使用します。
未加工のファイルパスを使用したコンテンツ アクセス
ストレージ関連の権限を持っていない場合は、File
API を使用して、アプリ固有のディレクトリ内のファイルと、アプリに紐付けされたメディア ファイルにアクセスできます。
アプリが File
API を使用してファイルにアクセスしようとした場合、必要な権限を持っていなければ、FileNotFoundException
が発生します。
Android 10 を実行しているデバイスで共有ストレージ内の他のファイルにアクセスする場合は、アプリのマニフェスト ファイルで requestLegacyExternalStorage
を true
に設定して、対象範囲別ストレージをオプトアウトすることおすすめします。
ネイティブ コードからのコンテンツ アクセス
特定のメディア ファイル(別のアプリと共有しているファイルや、ユーザーのメディア コレクション内のメディア ファイル)をネイティブ コードで処理することが必要な場合があります。
アプリで fopen()
などのネイティブ ファイル メソッドを使用してメディア ファイルを読み取るには、以下の手順を実施します。
- アプリのマニフェスト ファイルで
requestLegacyExternalStorage
をtrue
に設定します。 READ_EXTERNAL_STORAGE
権限をリクエストします。
これらのメディア ファイルに書き込みを行う必要がある場合は、ファイルに対応するファイル記述子を Java ベースまたは Koltin ベースのコードからネイティブ コードに渡します。次のコード スニペットは、メディア オブジェクトのファイル記述子をアプリのネイティブ コードに渡す方法を示しています。
Kotlin
val contentUri: Uri = ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cursor.getLong(BaseColumns._ID)) val fileOpenMode = "r" val parcelFd = resolver.openFileDescriptor(contentUri, fileOpenMode) val fd = parcelFd?.detachFd() // Pass the integer value "fd" into your native code. Remember to call // close(2) on the file descriptor when you're done using it.
Java
Uri contentUri = ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cursor.getLong(Integer.parseInt(BaseColumns._ID))); String fileOpenMode = "r"; ParcelFileDescriptor parcelFd = resolver.openFileDescriptor(contentUri, fileOpenMode); if (parcelFd != null) { int fd = parcelFd.detachFd(); // Pass the integer value "fd" into your native code. Remember to call // close(2) on the file descriptor when you're done using it. }
ネイティブ コードでファイルにアクセスする方法については、Android Dev Summit 2018 の講演の動画 Files for Miles(15 分 20 秒以降)をご覧ください。
アプリとメディア ファイルの紐付け
Android 10 以上をターゲットとするアプリで対象範囲別ストレージが有効になっている場合、システムはアプリを各メディア ファイルに紐付けます。これにより、ストレージ権限をリクエストしていない場合にアプリがアクセスできるファイルが決まります。各ファイルは 1 つのアプリにのみ紐付けることができます。したがって、写真、動画、オーディオ ファイルのいずれかのメディア コレクションに格納されるメディア ファイルをアプリが作成した場合、アプリはそのファイルにアクセスできます。
ただし、ユーザーがアプリをアンインストールして再インストールした場合、アンインストール前にアプリが作成したファイルにアクセスするには、READ_EXTERNAL_STORAGE
をリクエストする必要があります。この権限リクエストが必要になるのは、ファイルは新たにインストールされたバージョンではなく、以前インストールされたバージョンに紐付けられていると見なされるためです。
アイテムを追加する
既存のコレクションにメディア アイテムを追加するには、次のようなコードを呼び出します。
Kotlin
// Add a specific media item. val resolver = applicationContext.contentResolver // Find all audio files on the primary external storage device. // On API <= 28, use VOLUME_EXTERNAL instead. val audioCollection = MediaStore.Audio.Media.getContentUri( MediaStore.VOLUME_EXTERNAL_PRIMARY) // Publish a new song. val newSongDetails = ContentValues().apply { put(MediaStore.Audio.Media.DISPLAY_NAME, "My Song.mp3") } // Keeps a handle to the new song's URI in case we need to modify it // later. val myFavoriteSongUri = resolver .insert(audioCollection, newSongDetails)
Java
// Add a specific media item. ContentResolver resolver = getApplicationContext() .getContentResolver(); // Find all audio files on the primary external storage device. // On API <= 28, use VOLUME_EXTERNAL instead. Uri audioCollection = MediaStore.Audio.Media.getContentUri( MediaStore.VOLUME_EXTERNAL_PRIMARY); // Publish a new song. ContentValues newSongDetails = new ContentValues(); newSongDetails.put(MediaStore.Audio.Media.DISPLAY_NAME, "My Song.mp3"); // Keeps a handle to the new song's URI in case we need to modify it // later. Uri myFavoriteSongUri = resolver .insert(audioCollection, newSongDetails);
メディア ファイルの保留中ステータスを切り替える
メディア ファイルへの書き込みなど、時間がかかるオペレーションを実行するアプリでは、ファイルを処理している間、排他的アクセスを行うと便利です。Android 10 以上を実行しているデバイスでは、アプリで IS_PENDING
フラグの値を 1 に設定することにより、この排他的アクセス権を取得できます。IS_PENDING
の値を 0 に戻すまで、他のアプリはファイルを表示できなくなります。
次のコード スニペットは、前のコード スニペットを基にしています。このスニペットは、MediaStore.Audio
コレクションに対応するディレクトリに長い曲を保存するときに IS_PENDING
フラグを使用する方法を示しています。
Kotlin
// Add a media item that other apps shouldn't see until the item is // fully written to the media store. val resolver = applicationContext.contentResolver // Find all audio files on the primary external storage device. // On API <= 28, use VOLUME_EXTERNAL instead. val audioCollection = MediaStore.Audio.Media .getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) val songDetails = ContentValues().apply { put(MediaStore.Audio.Media.DISPLAY_NAME, "My Workout Playlist.mp3") put(MediaStore.Audio.Media.IS_PENDING, 1) } val songContentUri = resolver.insert(audioCollection, songDetails) resolver.openFileDescriptor(songContentUri, "w", null).use { pfd -> // Write data into the pending audio file. } // Now that we're finished, release the "pending" status, and allow other apps // to play the audio track. songDetails.clear() songDetails.put(MediaStore.Audio.Media.IS_PENDING, 0) resolver.update(songContentUri, songDetails, null, null)
Java
// Add a media item that other apps shouldn't see until the item is // fully written to the media store. ContentResolver resolver = getApplicationContext() .getContentResolver(); // Find all audio files on the primary external storage device. // On API <= 28, use VOLUME_EXTERNAL instead. Uri audioCollection = MediaStore.Audio.Media.getContentUri( MediaStore.VOLUME_EXTERNAL_PRIMARY); ContentValues songDetails = new ContentValues(); newSongDetails.put(MediaStore.Audio.Media.DISPLAY_NAME, "My Workout Playlist.mp3"); newSongDetails.put(MediaStore.Audio.Media.IS_PENDING, 1); Uri songContentUri = resolver .insert(audioCollection, songDetails); try (ParcelableFileDescriptor pfd = resolver.openFileDescriptor(longSongContentUri, "w", null)) { // Write data into the pending audio file. } // Now that we're finished, release the "pending" status, and allow other apps // to play the audio track. songDetails.clear(); songDetails.put(MediaStore.Audio.Media.IS_PENDING, 0); resolver.update(longSongContentUri, songDetails, null, null);
ファイルの場所に関するヒントを提供する
Android 10 を実行しているデバイスにアプリがメディアを保存する際、メディアはデフォルトではタイプに基づいて整理されます。たとえば、新しい画像ファイルは、デフォルトでは MediaStore.Images
コレクションに対応する Environment.DIRECTORY_PICTURES
ディレクトリに配置されます。
ファイルを保存するべき特定の場所(Pictures/MyVacationPictures という名前のフォトアルバムなど)をアプリが認識している場合は、MediaColumns.RELATIVE_PATH
を設定して、新しく書き込まれたファイルを保存する場所のヒントをシステムに提供できます。
アイテムを更新する
アプリが所有するメディア ファイルを更新するには、次のようなコードを実行します。
Kotlin
// Updates an existing media item. val mediaId = // MediaStore.Audio.Media._ID of item to update. val resolver = applicationContext.contentResolver // When performing a single item update, prefer using the ID val selection = "${MediaStore.Audio.Media._ID} = ?" // By using selection + args we protect against improper escaping of // values. val selectionArgs = arrayOf(mediaId.toString()) // Update an existing song. val updatedSongDetails = ContentValues().apply { put(MediaStore.Audio.Media.DISPLAY_NAME, "My Favorite Song.mp3") } // Use the individual song's URI to represent the collection that's // updated. val numSongsUpdated = resolver.update( myFavoriteSongUri, updatedSongDetails, selection, selectionArgs)
Java
// Updates an existing media item. long mediaId = // MediaStore.Audio.Media._ID of item to update. ContentResolver resolver = getApplicationContext() .getContentResolver(); // When performing a single item update, prefer using the ID String selection = MediaStore.Audio.Media._ID + " = ?"; // By using selection + args we protect against improper escaping of // values. Here, "song" is an in-memory object that caches the song's // information. String[] selectionArgs = new String[] { getId().toString() }; // Update an existing song. ContentValues updatedSongDetails = new ContentValues(); updatedSongDetails.put(MediaStore.Audio.Media.DISPLAY_NAME, "My Favorite Song.mp3"); // Use the individual song's URI to represent the collection that's // updated. int numSongsUpdated = resolver.update( myFavoriteSongUri, updatedSongDetails, selection, selectionArgs);
対象範囲別ストレージが使用できない場合または有効になっていない場合、上記のコード スニペットで示したプロセスは、アプリが所有していないファイルでも機能します。
他のアプリのメディア ファイルを更新する
対象範囲別ストレージを使用しているアプリでは、通常、別のアプリがメディアストアに書き込んだメディア ファイルを更新することはできません。
ただし、ファイルの変更についてユーザーの同意を得ることは可能です。そのためには、まず、プラットフォームがスローする RecoverableSecurityException
をキャッチします。次に、該当アイテムへの書き込みアクセス権をアプリに付与するようユーザーにリクエストします。次のコード スニペットをご覧ください。
Kotlin
// Apply a grayscale filter to the image at the given content URI. try { contentResolver.openFileDescriptor(image-content-uri, "w")?.use { setGrayscaleFilter(it) } } catch (securityException: SecurityException) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val recoverableSecurityException = securityException as? RecoverableSecurityException ?: throw RuntimeException(securityException.message, securityException) val intentSender = recoverableSecurityException.userAction.actionIntent.intentSender intentSender?.let { startIntentSenderForResult(intentSender, image-request-code, null, 0, 0, 0, null) } } else { throw RuntimeException(securityException.message, securityException) } }
Java
try { ParcelFileDescriptor imageFd = getContentResolver() .openFileDescriptor(image-content-uri, "w"); setGrayscaleFilter(imageFd); } catch (SecurityException securityException) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { RecoverableSecurityException recoverableSecurityException; if (securityException instanceof RecoverableSecurityException) { recoverableSecurityException = (RecoverableSecurityException)securityException; } else { throw new RuntimeException( securityException.getMessage(), securityException); } IntentSender intentSender =recoverableSecurityException.getUserAction() .getActionIntent().getIntentSender(); startIntentSenderForResult(intentSender, image-request-code, null, 0, 0, 0, null); } else { throw new RuntimeException( securityException.getMessage(), securityException); } }
アプリが作成していないメディア ファイルを変更する必要が生じるたびに、このプロセスを実行します。
アプリの別のユースケースに対象範囲別ストレージを適用できない場合は、機能リクエストを提出し、プラットフォームが提供するアプリ互換性機能を使用してください。
アイテムを削除する
アプリにとって不要になったアイテムをメディアストアから削除するには、次のコード スニペットに示すようなロジックを使用します。
Kotlin
// Remove a specific media item. val resolver = applicationContext.contentResolver // URI of the image to remove. val imageUri = "..." // WHERE clause. val selection = "..." val selectionArgs = "..." // Perform the actual removal. val numImagesRemoved = resolver.delete( imageUri, selection, selectionArgs)
Java
// Remove a specific media item. ContentResolver resolver = getApplicationContext() getContentResolver(); // URI of the image to remove. Uri imageUri = "..."; // WHERE clause. String selection = "..."; String[] selectionArgs = "..."; // Perform the actual removal. int numImagesRemoved = resolver.delete( imageUri, selection, selectionArgs);
対象範囲別ストレージが使用できない場合または有効になっていない場合は、上記のコード スニペットを使用して、他のアプリが所有するファイルを削除できます。一方、対象範囲別ストレージが有効になっている場合は、メディア アイテムを更新するセクションで説明しているように、アプリが削除するファイルごとに RecoverableSecurityException
をキャッチする必要があります。
アプリの別のユースケースに対象範囲別ストレージを適用できない場合は、機能リクエストを提出し、プラットフォームが提供するアプリ互換性機能を使用してください。
メディアストアの代替手段が必要なユースケース
アプリが主として次のいずれかの機能を実行する場合は、MediaStore
API の代替手段を検討してください。
メディア ファイルのグループを管理する
一般的に、メディア作成アプリはディレクトリ階層を使用してファイルのグループを管理します。この機能をアプリで提供するには、ドキュメントとその他のファイルに保存およびアクセスする方法のガイドで説明されている ACTION_OPEN_DOCUMENT_TREE
インテント アクションを使用します。
他の種類のファイルを処理する
メディア コンテンツ以外のデータも含むドキュメントとファイル(EPUB 拡張子や PDF 拡張子を持つファイルなど)を処理するアプリでは、ドキュメントとその他のファイルを保存およびアクセスする方法のガイドで説明されている ACTION_OPEN_DOCUMENT
インテント アクションを使用します。
コンパニオン アプリでファイル共有を使用する
メッセージ アプリやプロフィール アプリなどのコンパニオン アプリのスイートを提供する場合は、content://
URI を使用してファイル共有をセットアップします。このワークフローは、セキュリティに関するおすすめの方法でもあります。
参考情報
メディアの保存およびアクセス方法については、以下のリソースをご覧ください。
サンプル
- MediaStore: GitHub で入手可能です。