android - 如何创建其他应用程序(Polaris Office)只能读取的文件?

标签 android android-intent android-sdcard android-file android-permissions

这是我在我的应用程序中尝试做的事情。我下载文件(docx、pptx、pdf、mov 等)并将它们存储在 File 中。下载文件后,我希望用户能够打开并阅读它。 我不希望用户能够修改文件!

这是我尝试实现这一目标的方法。

            String uri =   nameFileStatic + extension;
            RestClientGetAsFile client = new RestClientGetAsFile(url, getActivity(), uri) {
                @Override
                protected void onPostExecute(File results) {
                    if (results != null) {
                        if (results.exists()) {
                            Uri path = Uri.fromFile(results);
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(path, type); //type
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            try {
                                startActivity(intent);
                            } catch (ActivityNotFoundException e) {
                                Toast.makeText(DescriberAttachments.this.getActivity(),
                                        "No Application Available to View file with extension " + extension, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
            };
            client.execute();

基本上,我在 AsyncTask 实例中下载文件。然后在 onPostExecute() 方法中,我使用 Intent 打开文件。

现在的问题是:将文件存储在哪里?这是我尝试过的:

  • uri = getDir("SLIMS", Context.MODE_WORLD_READABLE ).getAbsolutePath() + "/Attachments/myfile.docx"。在保存文件之前,我总是确保目录存在。
File directoryMain = new File(getDir("SLIMS", Context.MODE_PRIVATE).getAbsolutePath());
directoryMain.mkdir();
File directoryAttachments = new File( getDir("SLIMS",  Context.MODE_PRIVATE).getAbsolutePath() + "/Attachments");
directoryAttachments.mkdir();

不幸的是,之后我无法打开该文件...我收到一条消息错误(来自 Polaris Office),但在我的日志中找不到任何相关消息。

  • uri = getFilesDir() + "/Attachments/myfile.docx". 我遇到了与前一点完全相同的错误。

  • uri = Environment.getExternalStorageDirectory() + "/Attachments/myfile.docx"。这次我可以在 Polaris Office 中打开文件,但我无法将 File 设为只读。我尝试了 myFile.setReadOnly()myFile.setReadable(true)myFile.setWritable(false) 但我仍然能够修改最后归档。

所以我想现在我仍会将这些文件存储在 sdcard 中,但我对写入权限感到非常恼火。

有什么建议吗?

最佳答案

创建一个 ContentProvider在您的应用程序中并启动查看器应用程序并引用内容方案,例如 content://com.mydomain.myapp/file/filename.jpg

关于android - 如何创建其他应用程序(Polaris Office)只能读取的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15973471/

相关文章:

android - ConstraintLayout 1.1.0(测试版)中链中的边距如何工作

android - 背景图片问题

android - 如何传递 Intent 要求用户选择任何应用程序扫描二维码?

android获取所有设备的所有外部存储路径

android - Environment.getExternalStorageDirectory() 获取硬件存储

android - 从 Firebase 数据库填充 ListView

Android 4.3 不显示低功耗蓝牙广告

android - Android 操作系统中可用的 IPC 机制有哪些?

java - 通过意图传递 mutableList

javascript - 如何使用phonegap打开android的SDCARD