WebView下载和查看.pdf文件不起作用

时间:2016-03-15 21:31:37

标签: pdf webview

我创建了我的网站的这个网络应用程序:www.smartpapers.ml/app/main.html

此页面完全响应,在浏览器上运行良好。这个网站是一个过去的纸质网站,人们从中下载.pdf文件。

现在,当我点击任何.pdf链接时,它什么都不做并保持空闲状态。

我附上了我的"主要Activity.java + content_main.xml + android_manifest.xml"

请详细说明此代码的错误。

感谢。

Content_Main.xml:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main"
tools:context="ml.smartpapers.pastpapers.MainActivity">

<WebView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/webView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
</RelativeLayout>

活动Main.Java

package ml.smartpapers.pastpapers;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; 
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
private WebView mywebview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);
    mywebview = (WebView) findViewById(R.id.webView);
    WebSettings websettings = mywebview.getSettings();
    websettings.setJavaScriptEnabled(true);
    mywebview.loadUrl("http://www.smartpapers.ml/app/main.html");
    mywebview.setWebViewClient(new WebViewClient());
    mywebview.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String    contentDisposition, String mimetype, long contentLength) {
            //start download
            DownloadPDF downloadPDF = new DownloadPDF();
            downloadPDF.execute(url, userAgent, contentDisposition);
        }
    });
}
private class DownloadPDF extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... sUrl) {
        try {
            URL url = new URL(sUrl[0]);

            File myDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS).toString()+"/myPDF");

            // create the directory if it does not exist
            if (!myDir.exists()) myDir.mkdirs();

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.connect();

            //get filename from the contentDisposition
            String filename = null;
            Pattern p = Pattern.compile("\"([^\"]*)\"");
            Matcher m = p.matcher(sUrl[2]);
            while (m.find()) {
                filename = m.group(1);
            }

            File outputFile = new File(myDir, filename);

            InputStream input   = new BufferedInputStream(connection.getInputStream());
            OutputStream output = new FileOutputStream(outputFile);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                output.write(data, 0, count);
            }
            connection.disconnect();
            output.flush();
            output.close();
            input.close();

            // displayPdf();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
@Override
public void onBackPressed() {
    if (mywebview.canGoBack()) {
        mywebview.goBack();
    } else {
        super.onBackPressed();
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

1 个答案:

答案 0 :(得分:1)

use google pdf view instead, works fine without download on your webview.

                        String myPdfUrl = "http://www.pittmath.com/resources/Ultimate%20Circular%20Motion%20Review.pdf";
                        String url = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;
                         mywebview = (WebView) findViewById(R.id.webView);
WebSettings websettings = mywebview.getSettings();
websettings.setJavaScriptEnabled(true);
mywebview.loadUrl(url);
mywebview.setWebViewClient(new WebViewClient());
相关问题