Android webview download and view pdf, xls or doc files

I'm making an android app that uses a webview to navigate through a specific website. The thing is that I want users to be able to view pdf, .xls or .doc documents that are in the website.

I have this code, but it opens the android browser instead of viewing the pdf file.

webView.setDownloadListener(new DownloadListener() {
    public void onDownloadStart(String url, String userAgent,
            String contentDisposition, String mimetype, long contentLength) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);

    }
});

Also, I tried using google docs viewer but this doesn't work either. It opens me the html of the link, it doesn't open the file! The website doesn't direct you to the link of the pdf, it only let you download it, that's why google doc viewer doesn't work.

I would like to open the file like the android browser. It downloads the file and then it opens it. How can I accomplish this? I thought using android download manager, but how do I download the file, open it and when the user close it delete that file? because I would like to download only temporary time.

Any ideas are welcome. Thanks for your time!


You'll have to download the files first, so Android can find an appropriate application to open them with, since Uri.parse(url) will give you a website address, which is normally assigned to the browser (and will therefore open in it).

To download the files, you can use the DownloadManager -service or write your own code to do so. Once you have the file in a temporary location, you can open it by using your above method.

If you want to delete the file after the user viewed it, one idea would be to do it in your activities onResume() -method, which will be called when the user navigates back from viewing the file (using the back-button).

Although, I would rather put the files in the internal cache and wipe it every now and then. Android will do a little house-keeping itself, too:

When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.

链接地址: http://www.djcxy.com/p/46764.html

上一篇: 如何在Web视图上启用缩放以使用PDF(Android)加载URL?

下一篇: Android webview下载并查看pdf,xls或doc文件