在compileSDK = 33 时,谷歌在安卓新增了 图片选择器 功能,支持单选、多选、选图片、视频等操作,并且不需要额外获取照片/音频权限。
具体实现如下:
1:请求
- Log.d(TAG, "Build.VERSION.SDK_INT" + Build.VERSION.SDK_INT);
- if (Build.VERSION.SDK_INT >= 33) {
- //图片选择器单选
- // Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
- // 在complieSDK32已废弃
- // startActivityForResult(intent, PHOTO_PICKER_REQUEST_CODE);
- //图片选择器多选
- final int maxNumPhotosAndVideos = 3;
- Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
- // intent.setType("video/*");//仅选择视频
- intent.setType("image/*");//仅选择图片
- intent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, maxNumPhotosAndVideos);
- launcher.launch(intent);
- } else {
- //我们需要自己开发
- }
2:响应
2.1单选:
- @Override
- protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (resultCode == RESULT_OK) {
- if (requestCode == PHOTO_PICKER_REQUEST_CODE) {
- Uri currentUri = null;
- if (data != null) {
- currentUri = data.getData();
- binding.image.setImageURI(currentUri);
- }
- Log.d(TAG, "currentUri:" + currentUri);
- }
- }
- }
2.2多选:
- launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
- new ActivityResultCallback
() { - @Override
- public void onActivityResult(ActivityResult result) {
- if (result != null) {
- if (result.getData() != null && result.getResultCode() == RESULT_OK) {
- Intent intent = result.getData();
- for (int i = 0; i < intent.getClipData().getItemCount(); i++) {
- Uri uri = intent.getClipData().getItemAt(i).getUri();
- Log.d(TAG, "multiple current Uri:" + uri);
- // Do stuff with each photo/video URI.
- }
- }
- }
- }
- });