简体   繁体   English

无法从 ActivityResultContracts.CreateDocument() 的内容 uri 中获取文件类型

[英]Can't get filetype from content uri from ActivityResultContracts.CreateDocument()

I am using ActivityResultLauncher to allow the user to select a file in which I will save a bitmap.我正在使用 ActivityResultLauncher 允许用户选择一个文件,我将在其中保存位图。 I need to get the file extension of the file the user selected so that I can set the Bitmap.CompressFormat when I save the Bitmap.我需要获取用户选择的文件的文件扩展名,以便在保存位图时设置 Bitmap.CompressFormat。 Here is my code:这是我的代码:

    private ActivityResultLauncher<String> activityResultLauncher =
                registerForActivityResult(new ActivityResultContracts.CreateDocument(),
                new ActivityResultCallback<Uri>() {
                    @Override
                    public void onActivityResult(Uri uri) {
                        Timber.d("Result = %s", uri.toString());
                        OutputStream outputStream = null;
                        Bitmap bitmap = cameraViewModel.getImage();
                        try {
                            ContentResolver contentResolver = mainActivity.getContentResolver();
                            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
                            String type = mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
                            outputStream = contentResolver.openOutputStream(uri);
                            if (outputStream != null && bitmap != null) {
                                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                                outputStream.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

The type is always returned as null, is there anyway to get past the opaqueness of the content uri and see the actual filename该类型始终返回为 null,是否有通过内容 uri 的不透明性并查看实际文件名的方法

Get rid of MimeTypeMap and call getType() on the ContentResolver .摆脱MimeTypeMapContentResolver上调用getType()

The type is always returned as null, is there anyway to get past the opaqueness of the content uri and see the actual filename该类型始终返回为 null,是否有通过内容 uri 的不透明性并查看实际文件名的方法

No, because it is not necessarily a file.不,因为它不一定是文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM