【问题标题】:how to make intent.setType for pdf,xlsx and txt file android?如何为 pdf、xlsx 和 txt 文件制作intent.setType android?
【发布时间】:2015-05-12 18:26:11
【问题描述】:

我只想从存储中选择 pdf、xlsx 和 txt 文件,但 intent.setType 只能执行一个文件(例如,仅 .txt 文件(或)仅 pdf 文件)。是否可以通过编码intent.setType()来获取所有三个文件,有没有办法?

这是我的一些代码。

  private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select txt file"),
                0);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog

    }
}

【问题讨论】:

标签: android android-intent


【解决方案1】:

您可以使用 Intent.ACTION_OPEN_DOCUMENT,

每个文档都表示为由 DocumentsProvider 支持的 content:// URI,可以使用 openFileDescriptor(Uri, String) 将其作为流打开,或查询 DocumentsContract.Document 元数据。

所有选定的文档都将返回给调用应用程序,并授予持久的读写权限。如果您想在设备重启后保持对文档的访问权限,则需要使用 takePersistableUriPermission(Uri, int) 显式获取持久权限。

调用者必须通过setType(String) 指明可接受的文档 MIME 类型。例如,要选择照片,请使用image/*。如果可以接受多个不相交的 MIME 类型,请在 EXTRA_MIME_TYPESsetType(String)*/* 中定义它们。

更多详情请参考此链接

http://developer.android.com/reference/android/content/Intent.html#ACTION_OPEN_DOCUMENT

请注意,这仅适用于 API 级别 19+。

【讨论】:

    【解决方案2】:

    您似乎只是想看看是否可以解决这些意图。 这可能是更好的方法:

     private void showFileChooser() {
    
        Intent intentPDF = new Intent(Intent.ACTION_GET_CONTENT);
        intentPDF.setType("application/pdf");
        intentPDF.addCategory(Intent.CATEGORY_OPENABLE);
    
        Intent intentTxt = new Intent(Intent.ACTION_GET_CONTENT);
        intentTxt.setType("text/plain");
        intentTxt.addCategory(Intent.CATEGORY_OPENABLE);
    
        Intent intentXls = new Intent(Intent.ACTION_GET_CONTENT);
        intentXls.setType("application/x-excel");
        intentXls.addCategory(Intent.CATEGORY_OPENABLE);
    
        PackageManager packageManager = getPackageManager();
    
        List activitiesPDF = packageManager.queryIntentActivities(intentPDF,
        PackageManager.MATCH_DEFAULT_ONLY);
        boolean isIntentSafePDF = activitiesPDF.size() > 0;
    
        List activitiesTxt = packageManager.queryIntentActivities(intentTxt,
        PackageManager.MATCH_DEFAULT_ONLY);
        boolean isIntentSafeTxt = activitiesTxt.size() > 0;
    
        List activitiesXls = packageManager.queryIntentActivities(intentXls,
        PackageManager.MATCH_DEFAULT_ONLY);
        boolean isIntentSafeXls = activitiesXls.size() > 0;
    
        if (!isIntentSafePDF || !isIntentSafeTxt || !isIntentSafeXls){
    
            // Potentially direct the user to the Market with a Dialog
    
        }
    
    }
    

    参考资料:

    http://developer.android.com/training/basics/intents/sending.html

    How do I determine if Android can handle PDF

    【讨论】:

      【解决方案3】:

      您应该使用系统函数来查找您尝试访问的文件的特定 mimeType(如“application/pdf”)。如果您正在处理任何未知类型,则可能很难找到该类型。希望这段代码能救你!

      String url=Environment.getExternalStorageDirectory().getAbsolutePath()+"/Saves/contacts.vcf";
      File file = new File(url);
      Intent intent = new Intent(Intent.ACTION_VIEW);
      String mimeType=MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
      intent.setDataAndType(Uri.fromFile(file), mimeType);
      Intent intent1 = Intent.createChooser(intent, "Open With");
      startActivity(intent1);
      

      来源HERE

      【讨论】:

        【解决方案4】:
        intent.setType("image/*|application/pdf|audio/*");
        

        也许这就是你想要的。

        【讨论】:

        • 这是否记录在某处?当我尝试像这样组合多种类型时,意图没有选择任何文件类型。
        • 是的,它更清晰,但不适用于 '|'接线员,我试过了,没用。
        【解决方案5】:

        您应该检查此链接http://www.androidsnippets.com/open-any-type-of-file-with-default-intent.html。还要通读 Mime Type。

        这就是我为任何文件或选定的 mime 类型文件实现的方式

        String[] mimeTypes =
        {"image/*","application/pdf","application/msword","application/vnd.ms-powerpoint","application/vnd.ms-excel","text/plain"};
        
        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));
        }
        startActivityForResult(Intent.createChooser(intent,"ChooseFile"), 0);
        

        【讨论】:

          【解决方案6】:

          @Fatehali Asamadi 的方式还可以,但需要添加一些东西以供适当使用。 对于 Microsoft 文档(.doc 或 .docx)、(.ppt 或 .pptx)、(.xls 或 .xlsx)扩展名都使用。要支持或浏览这些扩展,您需要添加更多 mimeType。

          使用以下方法浏览文档,其中 REQUEST_CODE_DOC 为 onActivityResult(final int requestCode, final int resultCode,final Intent data) @Override 方法的 requestCode。

          private void browseDocuments(){
          
              String[] mimeTypes =
                      {"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
                              "application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
                              "application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
                              "text/plain",
                              "application/pdf",
                              "application/zip"};
          
              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));
              }
              startActivityForResult(Intent.createChooser(intent,"ChooseFile"), REQUEST_CODE_DOC);
          
          }
          

          您可以从 Here 获得清晰的概念并添加所需的 mimeTypes

          【讨论】:

          • 在使用此代码时,我无法在应用程序中查看文档。你能帮忙吗
          • 我的应用支持 Kitkat 及更高版本。所以,我只使用第一个逻辑条件。但是,不知何故,它显示了所有内容,而不仅仅是预期的内容。我怀疑这条线intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");。它不是让它显示一切吗?
          • 该行的目的是什么? intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "/");.
          • 花了太多时间寻找 docx Mime 类型“application/vnd.openxmlformats-officedocument.wordprocessingml.document”,这是我需要的 CrossFilePicker.Current.PickFile() allowedTypes 参数。谢谢:)
          • 使用此代码检测 mimetype File file = new File(filePath);字符串扩展 = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()); String mimeType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
          【解决方案7】:

          简单的解决办法是

             Intent gallery=new Intent();
                  gallery.setType("application/*");
                  gallery.setAction(Intent.ACTION_GET_CONTENT);
                  startActivityForResult(gallery,pick);
          

          注意:pick 是 int 变量。

          【讨论】:

            猜你喜欢
            • 2015-05-12
            • 2019-05-28
            • 2019-04-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-12-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多