使用单一意图拾取图像和Pdf



我知道我们可以使用以下

  1. 拾取图像:intent.setType("image/*")
  2. 选择PDF文件:intent.setType("application/PDF")

那么,有没有什么方法可以让我们通过单一的意图选择任何单一的实体,无论是pdf还是图像

这里只是一个例子:

private Intent getFileChooserIntent() {
    String[] mimeTypes = {"image/*", "application/pdf"};
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
        if (mimeTypes.length > 0) {
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        }
    } else {
        String mimeTypesStr = "";
        for (String mimeType : mimeTypes) {
            mimeTypesStr += mimeType + "|";
        }
        intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
    }
    return intent;
}

在我的情况下,上面的答案不起作用,经过一个小时的尝试和错误,这是我的工作解决方案:

fun getFileChooserIntentForImageAndPdf(): Intent {
        val mimeTypes = arrayOf("image/*", "application/pdf")
        val intent = Intent(Intent.ACTION_GET_CONTENT)
                .setType("image/*|application/pdf")
                .putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
        return intent
    }

希望可以帮助别人。

最新更新