Android Webview: Download Files Like Browsers Do

Android webview: download files like browsers do

Finally i decided to look for the
DownloadHandler from the Android Stock Browser code.
The only noticeable lack in my code was cookie (!!!).

Here's my final working version (DownloadManager method):

    wv.setDownloadListener(new DownloadListener() {
@Override
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) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}
});

How to download files like the native browser with Xamarin WebView on Android?

You could try the code below to use the custom renderer to download file via WebView.

[assembly: ExportRenderer(typeof(Xamarin.Forms.WebView), 
typeof(UpgradeWebViewRenderer))]
namespace App8.Droid
{
public class UpgradeWebViewRenderer : ViewRenderer<Xamarin.Forms.WebView, global::Android.Webkit.WebView>
{
public UpgradeWebViewRenderer(Context context) : base(context)
{

}

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);

if (this.Control == null)
{
var webView = new global::Android.Webkit.WebView(this.Context);
webView.SetWebViewClient(new WebViewClient());
webView.SetWebChromeClient(new WebChromeClient());
WebSettings webSettings = webView.Settings;
webSettings.JavaScriptEnabled = true;
webView.SetDownloadListener(new CustomDownloadListener());
this.SetNativeControl(webView);
var source = e.NewElement.Source as UrlWebViewSource;
if (source != null)
{
webView.LoadUrl(source.Url);
}
}
}
}

public class CustomDownloadListener : Java.Lang.Object, IDownloadListener
{
public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
{
DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
request.SetDestinationInExternalFilesDir(Forms.Context, Android.OS.Environment.DirectoryDownloads, "hello.jpg");
DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Android.App.Application.DownloadService);
dm.Enqueue(request);
}
}

}

How to Download a file in App with webview component?

As I said, if you want to download the file inside your webview, you should try this:

myWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(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);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name of your file");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
//you could show a message here

}
});

Don't forget to add this permission on your manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

And if you are using Android > 5 , you have to ask for permissions :)

Link: https://developer.android.com/training/permissions/requesting.html

How to download image from Webview to custom/private folder instead of Download folder in Android

try this

mywebView.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);

File folder = new File("/storage/emulated/0/Folder_Name");
if (!folder.exists()) {
folder.mkdirs();
System.out.println("Directory created");
} else {
System.out.println("Directory is not created");
}
request.setDestinationInExternalPublicDir("Folder_Name","Wallpaper.jpg");

DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

dm.enqueue(request);

}
});

Download file inside WebView

Have you tried?

mWebView.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);
}
});

Example Link: Webview File Download - Thanks @c49

How to download PDF file through Android Web View?

This guy from youtube solved it for me.

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);
}
});

But the issue is that the app is redirecting to chrome to load the URL and letting me download the file. Is there any other way to load the URL in the background and download the file?

Hope it helps someone..

File Download from Webview is not working in android, I am trying this way,

Based on the comments and discussion from the chat.

I have noticed that shouldOverrideUrlLoading is not being called. As, per the android documentation shouldOverrideUrlLoading

Give the host application a chance to take over the control when a new
url is about to be loaded in the current WebView

But in your case since url doesn't change in WebView address bar while clicking any of the three links. It just call javascript code javascript:__doPostBack('lnkPDF',''), which calls the post method to generate the file. If you to want use DownloadManager to download file while showing notification in notification area, you need to create dynamic static url for files like http:// or https://. E.g. http://www.somedomain/may_be_session_id/some_random_file_number_valid_for_some_time_only/file_name.pdf.

In addition to the above, let the web page change or redirect to new url, only then you will be able to capture urls in shouldOverrideUrlLoading.

Try changing your implementation of return in shouldOverrideUrlLoading to True if the host application wants to leave the current WebView and handle the url itself, otherwise return false.



Related Topics



Leave a reply



Submit