写真選択ツール

コレクションでコンテンツを整理 必要に応じて、コンテンツの保存と分類を行います。
デバイス上のメディア ファイルとともに写真選択ツール ダイアログが表示されます。アプリと共有する写真を選択します。
図 1. 写真選択ツールは、写真をアプリと共有するための直感的な UI です。

写真選択ツールは、メディア ライブラリが日付が新しい順に表示される、閲覧可能かつ検索可能なインターフェースです。プライバシーに関するおすすめの方法についての Codelab で説明されているように、写真選択ツールでは、メディア ライブラリ全体ではなく、選択した画像と動画にのみアクセスを許可するという安全な方法が取られています。

このツールは自動的に更新されるため、コードを変更しなくても、ユーザーは時間の経過にともないアプリの拡張された機能を利用できるようになります。

写真選択ツールは、以下の条件を満たしているデバイスで利用できます。

Jetpack Activity コントラクトを使用する

写真選択ツールの統合を容易にするには、androidx.activity ライブラリのバージョン 1.6.1 以降を組み込みます。

次のアクティビティ結果コントラクトを使用して、写真選択ツールを起動します。

デバイスで写真選択ツールを使用できない場合、ライブラリは代わりに ACTION_OPEN_DOCUMENT インテントのアクションを自動的に呼び出します。このインテントは、Android 4.4(API レベル 19)以降を搭載しているデバイスでサポートされています。特定のデバイスで写真選択ツールが使用可能かどうかを確認するには、isPhotoPickerAvailable() を呼び出します。

メディア アイテムを 1 つ選択する

1 つのメディア アイテムを選択するには、次のコード スニペットに示すように、PickVisualMedia アクティビティ結果コントラクトを使用します。

Kotlin

// Registers a photo picker activity launcher in single-select mode.
val pickMedia = registerForActivityResult(PickVisualMedia()) { uri ->
    // Callback is invoked after the user selects a media item or closes the
    // photo picker.
    if (uri != null) {
        Log.d("PhotoPicker", "Selected URI: $uri")
    } else {
        Log.d("PhotoPicker", "No media selected")
    }
}

// Include only one of the following calls to launch(), depending on the types
// of media that you want to allow the user to choose from.

// Launch the photo picker and allow the user to choose images and videos.
pickMedia.launch(PickVisualMediaRequest(PickVisualMedia.ImageAndVideo))

// Launch the photo picker and allow the user to choose only images.
pickMedia.launch(PickVisualMediaRequest(PickVisualMedia.ImageOnly))

// Launch the photo picker and allow the user to choose only videos.
pickMedia.launch(PickVisualMediaRequest(PickVisualMedia.VideoOnly))

// Launch the photo picker and allow the user to choose only images/videos of a
// specific MIME type, such as GIFs.
val mimeType = "image/gif"
pickMedia.launch(PickVisualMediaRequest(PickVisualMedia.SingleMimeType(mimeType)))

Java

// Registers a photo picker activity launcher in single-select mode.
ActivityResultLauncher<PickVisualMediaRequest> pickMedia =
        registerForActivityResult(new PickVisualMedia(), uri -> {
    // Callback is invoked after the user selects a media item or closes the
    // photo picker.
    if (uri != null) {
        Log.d("PhotoPicker", "Selected URI: " + uri);
    } else {
        Log.d("PhotoPicker", "No media selected");
    }
});

// Include only one of the following calls to launch(), depending on the types
// of media that you want to allow the user to choose from.

// Launch the photo picker and allow the user to choose images and videos.
pickMedia.launch(new PickVisualMediaRequest.Builder()
        .setMediaType(PickVisualMedia.ImageAndVideo.INSTANCE)
        .build());

// Launch the photo picker and allow the user to choose only images.
pickMedia.launch(new PickVisualMediaRequest.Builder()
        .setMediaType(PickVisualMedia.ImageOnly.INSTANCE)
        .build());

// Launch the photo picker and allow the user to choose only videos.
pickMedia.launch(new PickVisualMediaRequest.Builder()
        .setMediaType(PickVisualMedia.VideoOnly.INSTANCE)
        .build());

// Launch the photo picker and allow the user to choose only images/videos of a
// specific MIME type, such as GIFs.
String mimeType = "image/gif";
pickMedia.launch(new PickVisualMediaRequest.Builder()
        .setMediaType(new PickVisualMedia.SingleMimeType(mimeType))
        .build());

複数のメディア ファイルを選択する

複数のメディア アイテムを選択するには、次のコード スニペットに示すように、選択可能なメディア ファイルの最大数を設定します。

Kotlin

// Registers a photo picker activity launcher in multi-select mode.
// In this example, the app allows the user to select up to 5 media files.
val pickMultipleMedia =
        registerForActivityResult(PickMultipleVisualMedia(5)) { uris ->
    // Callback is invoked after the user selects media items or closes the
    // photo picker.
    if (uris.isNotEmpty()) {
        Log.d("PhotoPicker", "Number of items selected: ${uris.size}")
    } else {
        Log.d("PhotoPicker", "No media selected")
    }
}

// For this example, launch the photo picker and allow the user to choose images
// and videos. If you want the user to select a specific type of media file,
// use the overloaded versions of launch(), as shown in the section about how
// to select a single media item.
pickMultipleMedia.launch(PickVisualMediaRequest(PickVisualMedia.ImageAndVideo))

Java

// Registering Photo Picker activity launcher with multiple selects (5 max in this example)
ActivityResultLauncher<PickVisualMediaRequest> pickMultipleMedia =
        registerForActivityResult(new PickMultipleVisualMedia(5), uris -> {
    // Callback is invoked after the user selects media items or closes the
    // photo picker.
    if (!uris.isEmpty()) {
        Log.d("PhotoPicker", "Number of items selected: " + uris.size());
    } else {
        Log.d("PhotoPicker", "No media selected");
    }
});

// For this example, launch the photo picker and allow the user to choose images
// and videos. If you want the user to select a specific type of media file,
// use the overloaded versions of launch(), as shown in the section about how
// to select a single media item.
pickMultipleMedia.launch(new PickVisualMediaRequest.Builder()
        .setMediaType(PickVisualMedia.ImageAndVideo.INSTANCE)
        .build());

写真選択ツールでユーザーに選択を求めることができるファイルの数は、プラットフォームによって上限が設定されています。この制限を参照するには、getPickImagesMaxLimit() を呼び出します。この制限は、写真選択ツールに対応していないデバイスでは無視されます。

メディア ファイルへのアクセス権を持続させる

メディア ファイルへのアクセス権がアプリに付与されるのは、デフォルトで、デバイスが再起動されるか、アプリが停止するまでです。バックグラウンドで大きなファイルをアップロードするなど、長い時間がかかる作業を実行する場合、このアクセス権が持続する時間を延長する必要があります。そのためには、次のように takePersistableUriPermission() メソッドを呼び出します。

Kotlin

val flag = Intent.FLAG_GRANT_READ_URI_PERMISSION
context.contentResolver.takePersistableUriPermission(uri, flag)

Java

int flag = Intent.FLAG_GRANT_READ_URI_PERMISSION;
context.contentResolver.takePersistableUriPermission(uri, flag);

写真選択ツールを利用できるかどうかを確認する

次のセクションでは、フレームワーク ライブラリを使用して、特定のデバイスで写真選択ツールを使用できるかどうかを確認する方法について説明します。このワークフローでは、サポート ライブラリに依存せずに、写真選択ツールの起動動作をカスタマイズできます。

フレームワークで提供されるバージョンの写真選択ツールを使用するには、次のロジックをアプリに追加します。

Kotlin

import android.os.ext.SdkExtensions.getExtensionVersion

private fun isPhotoPickerAvailable(): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        true
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        getExtensionVersion(Build.VERSION_CODES.R) >= 2
    } else {
        false
    }
}

fun handlePhotoPickerLaunch() {
    if (isPhotoPickerAvailable()) {
        // To launch the system photo picker, invoke an intent that includes the
        // ACTION_PICK_IMAGES action. Consider adding support for the
        // EXTRA_PICK_IMAGES_MAX intent extra.
    } else {
        // Consider implementing fallback functionality so that users can still
        // select images and videos.
    }
}

Java

import android.os.ext.SdkExtensions.getExtensionVersion;

private boolean isPhotoPickerAvailable() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        return true;
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        return getExtensionVersion(Build.VERSION_CODES.R) >= 2;
    } else
        return false;
    }
}

public void launchPhotoPicker() {
    if (isPhotoPickerAvailable()) {
        // To launch the system photo picker, invoke an intent that includes the
        // ACTION_PICK_IMAGES action. Consider adding support for the
        // EXTRA_PICK_IMAGES_MAX intent extra.
    } else {
        // Consider implementing fallback functionality so that users can still
        // select images and videos.
    }
}