Android - 阅读pdf并使用Intent显示它

Mit*_*hah 0 pdf android android-intent

我正在开发一个应用程序,因为我想从资产中显示一个pdf文件.我做了很多谷歌,并尝试了多种排列和组合,但没有工作.

码:

private void CopyReadAssets()
{
    AssetManager assetManager = getActivity().getAssets();

    InputStream in = null;
    OutputStream out = null;
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc.pdf");
    try
    {
        in = assetManager.open("abc.pdf");
        out = getActivity().openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    }
    catch (Exception e)
    {
        Log.e("tag", e.getMessage());
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    startActivity(intent);
}

private void copyFile(InputStream in, OutputStream out) throws IOException
{
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1)
    {
        out.write(buffer, 0, read);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我点击列表时,我调用CopyReadAssets()函数然后它会提示我在哪个查看器中打开然后单击AdobeReader然后它会显示以下错误.

在此输入图像描述

Chi*_*iya 5

我检查了你的代码你必须改变一些错误,可能是你从这里复制了代码.

更换 AssetManager assetManager = getAssets();

代替 AssetManager assetManager = getActivity().getAssets();

直接使用 File file = new File(getFilesDir(), "abc.pdf");

代替

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc.pdf");

希望它适合你.!!!