我似乎无法弄清楚为什么我无法从WebView下载PDF。我在Android设备的下载管理器中收到下载失败的通知。但是,如果我使用不同的URL域,则可以下载。
不起作用的示例: http://somedomain/file.pdf并从http://somedomain加载WebView
有效的示例: http://somedomain2/file.pdf并从http://somedomain加载WebView
使用下载侦听器对WebView代码进行分段:
public class MyBillingFragment extends Fragment {
public MyBillingFragment() {
// Required empty public constructor
}
private static ProgressBar progressBar;
private static WebView webView;
private static View v;
private static final int REQUEST_EXTERNAL_STORAGE_RESULT = 1;
int requestCode;
String[] permissions;
int[] grantResults;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
getActivity().setTitle("MyBilling");
if(v == null) {
v = inflater.inflate(R.layout.fragment_billing, container, false);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) v.findViewById(R.id.webView);
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
} else {
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setBackgroundColor(Color.WHITE);
webView.setWebViewClient(new ourViewClient(){
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
webView.loadUrl("about:blank");
webView.loadUrl("file:///android_asset/error.html");
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if (progress < 100 && progressBar.getVisibility() == ProgressBar.GONE) {
progressBar.setVisibility(ProgressBar.VISIBLE);
webView.setVisibility(View.GONE);
}
if (progress == 100) {
progressBar.setVisibility(ProgressBar.GONE);
webView.setVisibility(View.VISIBLE);
}
}
});
webView.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
String data = getActivity().getIntent().getDataString();
if (Intent.ACTION_VIEW.equals(getActivity().getIntent().getAction())) {
webView.loadUrl(data);
} else {
webView.loadUrl("https://someurl");
}
if(ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
//------------------------COOKIE!!------------------------
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
//------------------------COOKIE!!------------------------
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getActivity().getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}
});
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(getActivity(),
"External storage permission required to save billing statements",
Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_EXTERNAL_STORAGE_RESULT);
}
if(requestCode == REQUEST_EXTERNAL_STORAGE_RESULT){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
//------------------------COOKIE!!------------------------
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
//------------------------COOKIE!!------------------------
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getActivity().getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(getActivity(), "External write permission has not been granted, cannot save file.",
Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
return v;
}
public class ourViewClient extends WebViewClient {
public void onPageFinished(WebView view, String url){
super.onPageFinished(view, url);
view.setVisibility(View.VISIBLE);
view.bringToFront();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
view.setVisibility(View.GONE);
}
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
}