繁体   English   中英

如何从Android中的存储读取文件?

[英]How to read file from storage in android?

我正在将一个excel文件保存到设备( Android 7 )的存储中,现在我想在用户单击按钮时打开excel文件,但是现在当我单击按钮时,应用程序将崩溃,而当我转到我的存储设备并打开时文件直接在我的应用程序外面没有问题! 如果我在任何代码行中都出错,请提供帮助,谢谢

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

文件目录:内部存储> 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);
}

从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="."/>

在外部Office应用中打开文件

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();

        }

暂无
暂无

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

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