Try adding download listener -
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, //Download folder
"download"); //Name of file
DownloadManager dm = (DownloadManager) getSystemService(
DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
I had same problem. Here is how I solved it. I extended WebViewClient:
import java.io.File;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyWebViewClient extends WebViewClient {
private Context context;
public MyWebViewClient(Context context) {
this.context = context;
}
@SuppressLint("NewApi")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains(".jpg")){
DownloadManager mdDownloadManager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
File destinationFile = new File(
Environment.getExternalStorageDirectory(),
getFileName(url));
request.setDescription("Downloading ...");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationUri(Uri.fromFile(destinationFile));
mdDownloadManager.enqueue(request);
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
public String getFileName(String url) {
String filenameWithoutExtension = "";
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".jpg");
return filenameWithoutExtension;
}
}
Of course you can modify url filter such as Uppercase etc other extensions...
In Fragment, add the line:
webPreview.setWebViewClient(new MyWebViewClient(getActivity()));
Or in Activity, add the line:
webPreview.setWebViewClient(new MyWebViewClient(this));
Of course modify webPreview to the WebView name you set
Make sure you add to WebView settings:
webSettings.setDomStorageEnabled(true);
if you have set:
webSettings.setBlockNetworkImage (false);