繁体   English   中英

Xamarin webview 网页无法下载文件 mSecurityInputMethodService is null

[英]Xamarin webview WebPage Cant download files mSecurityInputMethodService is null

我是 Xamarin 的新手,我将此示例用作我的应用程序的基础。 我刚刚注意到,当我单击链接下载文件时,它什么也没做,但我可以在控制台中看到下一个错误

mSecurityInputMethodService 是 null

我认为这是一种方法,但它根本没有做任何事情

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

你能给我一些建议吗?

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

这里正在运行 GIF。

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM