代码之家  ›  专栏  ›  技术社区  ›  Tejas Pandya

如何将Pdf从应用程序打开到默认查看器?

  •  -1
  • Tejas Pandya  · 技术社区  · 8 年前

    我正试图在Nougat中将pdf从应用程序打开到默认文档查看器。

    这不是重复的,因为我有不同的问题,所以读到最后。

    我试过的:

    在里面 AndroidManifest.xml文件

     <provider
                android:name="android.support.v4.content.FileProvider"
                android:authorities="${applicationId}.provider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths" />
            </provider>
    

    通用文件提供程序

    public class GenericFileProvider extends FileProvider {}
    

    提供程序路径.xml

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
           <external-path name="external_files" path="."/>
    </paths>
    

    按此打开ign pdf

     val file = File(Environment.getExternalStorageDirectory().toString()+"pdfname")
    
                val intent = Intent()
                intent.action = Intent.ACTION_VIEW
                val uri = FileProvider.getUriForFile(context,  BuildConfig.APPLICATION_ID + ".provider", file)
    
               context.grantUriPermission("com.google.android.apps.docs", uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
    
    
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    
                intent.setDataAndType(uri, "application/pdf")
                context.startActivity(intent)
    

    我的问题是:

    在查看我的pdf文件时,它的第一个字符已更改。 所以它会生成“找不到文件”异常

    它删除了我的pdf名称的第一个字符

     my file name is  : /storage/emulated/0on the matter of.pdf
     my uri is : content://mypackage.provider/root/storage/emulated/0on%20the%20matter%20of.pdf
    so pdf name is : n the matter of.pdf
    

    使用provider_path this时。

    <root-path
               name="root"
               path="/" />
    

     my file name is  : /storage/emulated/0on the matter of.pdf
     my uri is : content://mypackage.provider/root/storage/emulated/0on%20the%20matter%20of.pdf
    so pdf name is : 0on the matter of.pdf
    

    我应该怎么做才能得到正确的pdf名称。我应该在provider path中写些什么。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Tejas Pandya    8 年前

    感谢@VladyslavMatviienko和@greenapps。我已经解决了我的问题。

    正如@VladyslavMatviienko指出的。我传递了错误的文件路径。

    val file = File(Environment.getExternalStorageDirectory().toString()+"pdfname")
    

    而不是

    val file = File(Environment.getExternalStorageDirectory().toString()+"/pdfname")
    

    所以它显示了 java.io.FileNotFoundException: