Xamarin webview WebPage Cant download files mSecurityInputMethodService is null

I'm new to Xamarin, I'm using this example as a base for my on application. I just noticed when I click in a link to download files, it doesnt do anything, but i can see in the consoloe the next error

mSecurityInputMethodService is null

I saw this as an approach, but it didnt do anything at all

    private void WebView_OnNavigating(object sender, WebNavigatingEventArgs e)
    {
        if (e.Url.ToLower().Contains("forcesave=true") || e.Url.ToLower().Contains("pdf"))
        {
            var uri = new Uri(e.Url);
            Device.OpenUri(uri);
            e.Cancel = true;
        }
    }

Can you please give me some advice?

Upvotes: 0

Views: 518

Answers (1)

Leon Lu
Leon Lu

Reputation: 9234

Create a custom renderer for webview.

[assembly: ExportRenderer(typeof(Xamarin.Forms.WebView), 
     typeof(CustomWebViewRenderer))]
namespace TwoCollen.Droid
{
public class CustomWebViewRenderer : ViewRenderer<Xamarin.Forms.WebView, global::Android.Webkit.WebView>
{
    public CustomWebViewRenderer(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, "mydeddp.pdf");
        DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Android.App.Application.DownloadService);
        dm.Enqueue(request);
    }
}

Here is running GIF.

enter image description here

Upvotes: 1

Related Questions