【问题标题】:Xamarin webview WebPage Cant download files mSecurityInputMethodService is nullXamarin webview WebPage 无法下载文件 mSecurityInputMethodService 为空
【发布时间】:2019-11-21 05:35:55
【问题描述】:

我是 Xamarin 的新手,我使用这个 example 作为我的应用程序的基础。我刚刚注意到,当我单击一个链接下载文件时,它没有执行任何操作,但我可以在控制台中看到下一个错误

mSecurityInputMethodService 为空

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

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

你能给我一些建议吗?

【问题讨论】:

  • 你想从 web 视图下载文件吗?
  • 是的,用户将使用 WebView 浏览我的网站,有一些带有文件的 url

标签: c# android xamarin


【解决方案1】:

为 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。

【讨论】:

  • @David Alejandro García García 你试过上面的方法了吗?
  • 是的并且正在工作,但是现在当我单击返回按钮时它不起作用我创建了另一个问题stackoverflow.com/questions/59107967/…
猜你喜欢
  • 2014-08-13
  • 2020-09-22
  • 2016-11-29
  • 2020-03-10
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 2017-09-23
相关资源
最近更新 更多