在android webview中下载文件(pdf,ppt,xls)到没有浏览器的下载文件夹

时间:2015-02-17 18:13:55

标签: android pdf webview download android-download-manager

我正在开发一个包含webview的应用程序,在显示的webiste内部有一些pdf,xls和ppt文件,一旦触摸(onclick)就必须下载。现在我怎么做,因为我尝试了一些从stackoverflow接近这里,但没有一个工作。我知道我必须使用下载管理器下载它们,我不需要在我的应用程序中显示它们只是为了下载它们。 这是我用来显示我的webview的代码和包含这些文件的其中一个页面的截图。

        //Load webview
            moodleweb = (WebView) findViewById(R.id.moodlewebview);
            moodleweb.setWebViewClient(new WebViewClient());
            WebSettings webSettings = moodleweb.getSettings();
            webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
            moodleweb.loadUrl("http://moodle.ubt-uni.net/");
            webSettings.setJavaScriptEnabled(true);
moodleweb.getSettings().setCacheMode(moodleweb.getSettings().LOAD_DEFAULT);
            moodleweb.getSettings().setAppCacheEnabled(true);
            moodleweb.clearCache(false);
            moodleweb.setWebChromeClient(new WebChromeClient(){

                public void onProgressChanged(WebView view, int progress) {

                    progressBar.setProgress(progress);
                    if(progress == 100) {
                        progressBar.setVisibility(View.GONE);
                    }
                }
            });![enter image description here][2]
            backbutton = (Button) findViewById(R.id.backbutton);  
            backbutton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(moodleweb.canGoBack()){
                        moodleweb.goBack();
                    }else{
                        finish();
                    }
                }
            });

enter image description here

编辑2

确定@zepar,我按照你的指示行动得到了这个例外。可能是什么问题:

02-18 12:27:51.943    4972-5424/net.prdev.ubtsmismoodle E/MoodleActivity﹕ 
Exception:
    java.io.FileNotFoundException: /sdcard/downloadedFiels/pluginfile.php?file=%2F23496%2Fmod_resource%2Fcontent%2F1%2FOrari%20i%20transportit%20t%C3%AB%20studenteve%20Prizren%20-%20Prishtin%C3%AB%20dhe%20anasjelltas.pdf: open failed: ENOENT (No such file or directory)
            at libcore.io.IoBridge.open(IoBridge.java:456)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:127)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:116)
            at net.prdev.ubtsmismoodle.MoodleActivity$DownloadTask.doInBackground(MoodleActivity.java:145)
            at net.prdev.ubtsmismoodle.MoodleActivity$DownloadTask.doInBackground(MoodleActivity.java:125)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
            at libcore.io.Posix.open(Native Method)
            at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
            at libcore.io.IoBridge.open(IoBridge.java:442)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:127)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:116)
            at net.prdev.ubtsmismoodle.MoodleActivity$DownloadTask.doInBackground(MoodleActivity.java:145)
            at net.prdev.ubtsmismoodle.MoodleActivity$DownloadTask.doInBackground(MoodleActivity.java:125)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)

1 个答案:

答案 0 :(得分:1)

您可以扩展WebViewClient并覆盖shouldOverrideUrlLoading方法。在该方法中,您可以检查是否要处理请求或将其留给WebView

see the android documentation

修改

参考下面的评论,这是一个例子:

public class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.endsWith(".pdf") || url.endsWith(".xls") || url.endsWith(".ppt")) {
            Log.i(TAG, "download: " + url);
            // In this place you should handle the download
            return true;
        }
        return super.shouldOverrideUrlLoading(view, url);
    }
}

并将类的实例设置为WebView:

moodleweb.setWebViewClient(new MyWebViewClient());
moodleweb.loadUrl("http://moodle.ubt-uni.net/");

<强> EDIT2

下载文件的最简单方法是使用AsyncTask

private class DownloadTask extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            String filename = url.getFile();
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                Log.e(TAG, "Server didn't return 200. ");
                // handle error
                return null;
            }

            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/downloadedFiels/" + filename); // where to save file

            byte data[] = new byte[4096];
            int count;
            while ((count = input.read(data)) != -1) {
                if (isCancelled()) {
                    return null;
                }
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            // handle error
            Log.e(TAG, "Exception: ", e);
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException: ", e);
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }
}

要下载文件,你必须以url作为参数执行任务:

new DownloadTask().execute(url);

<强> EDIT3

我猜,这是因为路径不存在或无效。尝试介绍一些变化: 首先是文件名,我假设url看起来像这样:http://host/file.pdf不是php的参数。这不是正确的方法,但你可以试试这个:

String filename = URLDecoder.decode(sUrl[0].substring(sUrl[0].lastIndexOf("=")), "UTF-8");

// where to save file
File file = new File("/sdcard/downloadedFiels/" + filename);
file.mkdirs();
output = new FileOutputStream(file);