请告诉我任何知道如何在没有webview的情况下打开pdf网址的人或知道最佳做法或图书馆的人
pdf url = http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf
的示例答案 0 :(得分:0)
有方法:
强制下载并打开它:
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String aUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) {
fileName = URLUtil.guessFileName(aUrl, contentDisposition, mimetype); //returns a string of the name of the file THE IMPORTANT PART
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(aUrl));
request.allowScanningByMediaScanner();
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(aUrl);
request.addRequestHeader("Cookie", cookie);
request.setMimeType("application/pdf");
request.addRequestHeader("User-Agent", userAgent);
Environment.getExternalStorageDirectory();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
});
并且不要忘记在下载后添加这些方法以打开pdf:
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
openFile(fileName); }
};
protected void openFile(String fileName) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator +
fileName);
Uri path = Uri.fromFile(file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
}
}
同样不要忘记在:
中声明perrmission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
或者你只能
在意图中打开 :
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
两种解决方案都经过测试并且有效。