如何在android 14(Api 34)中打开图片库来选择图片?

问题描述 投票:0回答:1

我使用以下代码从图库中选择图像。它一直工作到 Android 13 (Api 33),但在 Android 14 (Api 34) 上无法工作(图库未打开)。

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        photoPickerIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        if (photoPickerIntent.resolveActivity(getPackageManager()) != null) {

            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, PICK_IMAGE_MULTIPLE);
        }

请帮助我。预先感谢。

android android-studio image-gallery imagepicker
1个回答
0
投票

这是我在我的项目中使用的,它适用于最新的android。我的有一个 firebase 上传部分,它可能包含在答案中,因此请使用它作为参考来帮助指导您。

 Uri FilePathUri;
 int Image_Request_Code = 7;
 private ActivityResultLauncher<String> imagePickerLauncher;

在 onCreate 中

 imagePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(),
            result -> {
                if (result != null) {
                    // Handle the selected image
                    FilePathUri = result;
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
                        imgView.setImageBitmap(bitmap);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    );
 btnBrowse.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            imagePickerLauncher.launch("image/*");

        }
    });

onCreate 之外

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == Image_Request_Code && resultCode == RESULT_OK && data != null && data.getData() != null) {

        FilePathUri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
            imgView.setImageBitmap(bitmap);
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}


public String GetFileExtension(Uri uri) {

    ContentResolver contentResolver = getContentResolver();
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));

}
© www.soinside.com 2019 - 2024. All rights reserved.