【问题标题】:How to read file from storage in android?如何从android中的存储中读取文件?
【发布时间】:2018-06-13 22:20:05
【问题描述】:

我正在将 excel 文件保存到设备 (Android 7) 的 storage 中,现在我想要当用户单击按钮时,将打开 excel 文件,但现在单击按钮时,应用程序将崩溃,而当我进入我的存储空间并直接在我的应用程序外部打开文件时,没有问题!如果我在任何代码行中有错误,请帮忙,谢谢

日志:android.os.FileUriExposedException:file:///storage/emulated/0/MessangerApp/MessangerDocuments/139703251134.xlsx 通过 Intent.getData() 暴露在应用程序之外 在 android.os.StrictMode.onFileUriExposed

文件目录:内部存储> MessangerApp > MessangerDoucments >Test.xlsx

这是我的代码:

   File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + Config.DOC_DIRECTORY_Name + filename);
            Uri path = Uri.fromFile(file);

            Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
            pdfOpenintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            pdfOpenintent.setDataAndType(path, "application/vnd.ms-excel");
            view.getContext().startActivity(pdfOpenintent);
}

【问题讨论】:

    标签: java android file uri


    【解决方案1】:

    从 Android N 开始,为了解决此问题,您需要使用 FileProvider API。

    <manifest ...>
    <application ...>
        <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>
    </application>
    

    创建 XML 文件 res/xml/provider_paths.xml

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

    在外部办公应用中打开文件

    File excelFile = new File(Environment.getExternalStorageDirectory(),"nameexcelFile.pdf");//File path
            if (excelFile.exists()) //Checking if the file exists or not
            {
                Uri path = Uri.fromFile(excelFile);
                Intent objIntent = new Intent(Intent.ACTION_VIEW);
                objIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(objIntent);//Starting the excel file viewer
            } else {
    
                Toast.makeText(getActivity(), "The file not exists! ", Toast.LENGTH_SHORT).show();
    
            }
    

    【讨论】:

    • 我想当按钮点击程序列表显示并选择office excel打开它,但你的代码结果是在provider_paths布局中显示内容对吗?
    • 要使用外部应用程序,您必须先访问文件路径,我更新了答案,再次检查
    • 我添加了您最后更新的代码,首先显示程序列表,但我找不到 office excel,所以我添加了 objIntent.setDataAndType(path, "application/vnd.ms-excel");这段代码的结果有我的帖子中写的prevoius错误
    猜你喜欢
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多