【问题标题】:Error while reading pdf using MODE_WORLD_READABLE?使用 MODE_WORLD_READABLE 阅读 pdf 时出错?
【发布时间】:2012-03-13 20:36:44
【问题描述】:

我制作了一个应用程序,它从服务器下载 pdf 并将其存储在

/data/data/<package_name>files

使用此代码:

FileOutputStream fos = openFileOutput(pdfFileName, Context.MODE_WORLD_READABLE);
fos.write(pdfAsBytes);
fos.close();

但是,当我从设备上已有的 pdf 阅读器应用程序读取这些文件时,有时会显示黑屏,有时会显示带有烦人字体的文件。我使用的代码是:

File file = new File("/data/data/<package_Name>/files/pdffile");
Uri path = Uri.fromFile(file);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
    startActivity(pdfIntent);
}
catch(Exception e)
{
    Log.e("Activity Not Found Exception",e.toString());
}

我已经在其他路径(在 sdcard 中)尝试使用相同文件的相同代码,它们工作正常。 请帮助我并告诉我应该出了什么问题。

应该有什么可能的方法来纠正它?

【问题讨论】:

    标签: android file pdf path


    【解决方案1】:

    只有两种方法可以实现你想要的:


    1) 使用 SDCARD

    您将下载的pdf 保存在某处SDCARD。像这样的:

    而不是创建文件:

    File pdfFile = new File(Environment.getExternalStorageDirectory(), "pdffile");
    FileOutputStream fos = new FileOutputStream(pdfFile);
    fos.write(pdfAsBytes);
    fos.close();
    ...
    

    你在创建 Intent 时使用pdfFile


    2) 使用自定义ContentProvider

    如果您仍然不想使用 SDCARD 存储,可以使用第二种方法。您可以使用您的应用程序的CacheDir(您将在那里下载您的文件)。这包括创建您自己的ContentProvider,然后您将能够将相应的 URI 传递给 pdfreader 应用程序。

    如何做到这一点的详细信息都是here


    没有其他已知的方法可以在 Android 的 3rd 方应用中打开任何下载的文件。

    【讨论】:

    • 您的声明不真实。确实,发布者想要使用的方法目前不鼓励,并且某些应用程序甚至可能拒绝尝试访问此类路径原则上 - 但是并不意味着 Android 会阻止他们这样做如果他们尝试
    【解决方案2】:

    你应该使用方法 android.content.Context.getFilesDir().

    返回文件系统上存储使用 openFileOutput(String, int) 创建的文件的目录的绝对路径。

    此代码适用于我:

    File file = new File(this.getFilesDir(), pdfFileName);
    Uri path = Uri.fromFile(file);
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
    pdfIntent.setDataAndType(path, "application/pdf");
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    try {
         startActivity(pdfIntent);
    } catch(ActivityNotFoundException e) {
         Log.e("Activity Not Found Exception",e.toString());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多