Xamarin webview WebPage 无法下载文件 mSecurityInputMethodService 为空 [英] Xamarin webview WebPage Cant download files mSecurityInputMethodService is null

查看:33
本文介绍了Xamarin webview WebPage 无法下载文件 mSecurityInputMethodService 为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Xamarin 的新手,我正在使用这个

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?

解决方案

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.

这篇关于Xamarin webview WebPage 无法下载文件 mSecurityInputMethodService 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆