
Công cụ chọn ảnh cung cấp giao diện có thể tìm kiếm, có thể xem hiển thị cho người dùng thư viện nội dung nghe nhìn sắp xếp theo trình tự từ mới nhất đến cũ nhất. Như đã đề cập trong lớp học lập trình về các phương pháp hay nhất về quyền riêng tư, công cụ chọn ảnh cung cấp cho người dùng một cách tích hợp an toàn để chỉ cấp cho ứng dụng quyền truy cập vào các hình ảnh và video đã chọn, thay vì toàn bộ thư viện nội dung nghe nhìn.
Công cụ này tự động cập nhật, cung cấp chức năng mở rộng cho người dùng ứng dụng theo thời gian mà không yêu cầu thay đổi mã.
Công cụ chọn ảnh hoạt động trên các thiết bị đáp ứng các tiêu chí sau:
- Chạy Android 11 (cấp độ API 30) trở lên
- Nhận các thay đổi đối với Thành phần hệ thống mô-đun thông qua Bản cập nhật hệ thống của Google
Sử dụng hợp đồng Hoạt động Jetpack
Để đơn giản hoá việc tích hợp công cụ chọn ảnh, hãy bao gồm cả thư viện androidx.activity
phiên bản 1.6.1 trở lên.
Sử dụng các hợp đồng kết quả hoạt động sau đây để khởi chạy công cụ chọn ảnh:
PickVisualMedia
, để chọn một hình ảnh hoặc video.PickMultipleVisualMedia
, để chọn nhiều hình ảnh hoặc video.
Nếu công cụ chọn ảnh không hoạt động trên một thiết bị, thì thư viện sẽ tự động gọi thao tác theo ý định ACTION_OPEN_DOCUMENT
. Ý định này được hỗ trợ trên các thiết bị chạy Android 4.4 (API cấp 19) trở lên. Bạn có thể xác minh xem công cụ chọn ảnh có hoạt động trên một thiết bị nhất định hay không bằng cách gọi isPhotoPickerAvailable()
.
Chọn một mục nội dung nghe nhìn
Để chọn một mục nội dung nghe nhìn, hãy sử dụng hợp đồng kết quả hoạt động của PickVisualMedia
, như trong đoạn mã sau:
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());
Chọn nhiều mục nội dung nghe nhìn
Để chọn nhiều mục nội dung nghe nhìn, hãy đặt số lượng tối đa tệp nội dung nghe nhìn có thể chọn như trong đoạn mã sau.
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());
Nền tảng này giới hạn số lượng tệp tối đa mà bạn có thể yêu cầu người dùng chọn trong công cụ chọn ảnh. Để xem giới hạn này, hãy gọi getPickImagesMaxLimit()
.
Trên những thiết bị không hỗ trợ công cụ chọn ảnh, giới hạn này sẽ bị bỏ qua.
Duy trì quyền truy cập vào tệp nội dung nghe nhìn
Theo mặc định, hệ thống sẽ cấp cho ứng dụng của bạn quyền truy cập vào các tệp nội dung nghe nhìn cho đến khi thiết bị khởi động lại hoặc ứng dụng ngừng hoạt động. Nếu ứng dụng của bạn thực hiện các tác vụ chạy trong thời gian dài, chẳng hạn như tải một tệp lớn lên trong nền, thì có thể bạn cần có quyền truy cập này lâu hơn. Để thực hiện việc này, hãy gọi phương thức 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);
Kiểm tra xem công cụ chọn ảnh có hoạt động hay không
Phần sau đây mô tả cách bạn có thể sử dụng thư viện khung để kiểm tra xem công cụ chọn ảnh có hoạt động trên một thiết bị nhất định hay không. Quy trình công việc này cho phép bạn tuỳ chỉnh hành vi khởi chạy của công cụ chọn ảnh mà không phụ thuộc vào thư viện hỗ trợ.
Để sử dụng phiên bản công cụ chọn ảnh đã có khung, hãy thêm phần sau vào ứng dụng:
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. } }