如何从assets文件夹中打开Android中的PDF文件?

前端之家收集整理的这篇文章主要介绍了如何从assets文件夹中打开Android中的PDF文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有人知道如何在 Android中打开PDF文件?我的代码看起来像这样:
public class SampleActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        CopyReadAssets();    
    }

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

        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(),"git.pdf");
        try {
            in = assetManager.open("git.pdf");
            out = 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.parse("file://" + getFilesDir() + "/git.pdf"),"application/pdf");

        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,read);
        }
    }
}

解决方法

以下是从资产文件夹打开pdf文件代码,但您必须在设备上安装pdf阅读器:
private void CopyAssets() {

        AssetManager assetManager = getAssets();

        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(),"fileName.pdf");
        try {
            in = assetManager.open("fileName.pdf");
            out = openFileOutput(file.getName(),e.getMessage());
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/fileName.pdf"),read);
        }
    }
原文链接:https://www.f2er.com/android/318551.html

猜你在找的Android相关文章