这个问题在这里已有答案:
从活动的oncreate()调用此方法。我应该编写什么代码才能进行下载?目前,从此代码中可以看到webview,其中有两个按钮。点击它们后,下载不会发生。请帮忙
private void openBrowser()
{
Uri uri = Uri.parse("googlechrome://navigate?url=" + urlString + mSelectedProductDetails.getTransIdValue());
Intent i = new Intent(Intent.ACTION_VIEW, uri);
// final String message;
if (i.resolveActivity(getActivity().getPackageManager()) == null) {
i.setData(Uri.parse(urlString + mSelectedProductDetails.getTransIdValue()));
message = urlString + mSelectedProductDetails.getTransIdValue();
}else
{
message = urlString+mSelectedProductDetails.getTransIdValue();}
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().getJavaScriptEnabled();
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
progress.setVisibility(View.INVISIBLE);
webView.loadUrl(message);
}
}
要下载文件,您需要在WebView中实现DownloadListener。
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
mUrl = url;
mUserAgent = userAgent;
mContentDisposition = contentDisposition;
mMimetype = mimetype;
mContentLength = contentLength;
if (isStoragePermissionGranted()) {
downloadFile(url, userAgent, contentDisposition, mimetype, contentLength);
}
}
});
下载您的文件
public void downloadFile(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
(URLUtil.guessFileName(url, contentDisposition, mimetype)));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();
}