首页 > 解决方案 > 用户从 Xamarin Android 中的 Webview 长按保存图像

问题描述

我已经在 Xamarin 中实现了一个带有自定义渲染器的 webview 页面来放大/缩小页面。问题是 android 中的 WebView 不允许保存任何已加载到 webView 中的图像,但是,使用相同的代码我可以在 iOS 上下载图像。

有什么办法,当用户长按Android的WebView上的图像时,我可以保存图像吗?提前致谢。

这是我正在使用的代码。

WebView自定义

this._WebView = new WebViewCustom
        {
            BackgroundColor = AppConfig.MenuBackgroundColor,
            VerticalOptions = LayoutOptions.FillAndExpand,
            HorizontalOptions = LayoutOptions.FillAndExpand,
            Source = new UrlWebViewSource
            {
                Url = url
            },
        };

WebViewCustomRenderer 类

[assembly: ExportRenderer(typeof(WebViewCustom), typeof(WebViewCustomRenderer))]
namespace PBL.App.Droid.Renderers
{
class WebViewCustomRenderer : WebViewRenderer
{
    public WebViewCustomRenderer(Context context) : base(context)
    {
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (Control != null)
        {
            Control.Settings.BuiltInZoomControls = true;
            Control.Settings.DisplayZoomControls = false;

            Control.Settings.SetSupportZoom(true);
            Control.Settings.AllowFileAccess = true;
            MessagingCenter.Subscribe<object, bool>(this, "zoom", (sender1, arg) => {
                Control.Settings.SetSupportZoom(arg);
            });
        }
        base.OnElementPropertyChanged(sender, e);
    }
    protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
    {
        if (Control != null)
        {
            Control.Settings.SetSupportZoom(true);
        }
        if(e.NewElement != null)
        {
            Control.Settings.AllowContentAccess = true;
            Control.Settings.AllowUniversalAccessFromFileURLs = true;
            Control.Settings.DomStorageEnabled = true;
            Control.Settings.JavaScriptEnabled = true;
            Control.Download += OnWebViewDownload;
        }
        base.OnElementChanged(e);
    }

    private void OnWebViewDownload(object sender, DownloadEventArgs e)
    {
        var source = Uri.Parse(e.Url);
        var request = new DownloadManager.Request(source);

        request.AllowScanningByMediaScanner();

        request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
        request.SetDestinationInExternalPublicDir(Environment.DirectoryDownloads, source.LastPathSegment);


    }
}
}

标签: androidxamarin.formswebviewwebclient

解决方案


你可以LongClick给WebView添加一个监听器,然后判断HitTestResult你在webview中按下的类型:</p>

[assembly: ExportRenderer(typeof(WebViewCustom), typeof(WebViewCustomRenderer))]
namespace PBL.App.Droid.Renderers
{
  class WebViewCustomRenderer : WebViewRenderer,Android.Views.View.IOnLongClickListener
   {
     Dialog dialog;
     Context _context;
     public WebViewCustomRenderer(Context context) : base(context)
      {
        _context = context;
      }

     protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
      {
        if (Control != null)
          {
            Control.Settings.BuiltInZoomControls = true;
            Control.Settings.DisplayZoomControls = false;

            Control.Settings.SetSupportZoom(true);
            Control.Settings.AllowFileAccess = true;
            MessagingCenter.Subscribe<object, bool>(this, "zoom", (sender1, arg) => {
            Control.Settings.SetSupportZoom(arg);
        });
    }
    base.OnElementPropertyChanged(sender, e);
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
    if (Control != null)
    {
        Control.Settings.SetSupportZoom(true);
    }
    if(e.NewElement != null)
    {
        Control.Settings.AllowContentAccess = true;
        Control.Settings.AllowUniversalAccessFromFileURLs = true;
        Control.Settings.DomStorageEnabled = true;
        Control.Settings.JavaScriptEnabled = true;
        //add long press listener
        Control.SetOnLongClickListener(this);
    }
    base.OnElementChanged(e);
}

  public bool OnLongClick(Android.Views.View v)
    {
        Android.Webkit.WebView.HitTestResult hitTestResult = ((Android.Webkit.WebView)v).GetHitTestResult();
        if (hitTestResult.Type == HitTestResult.ImageType ||
                hitTestResult.Type == HitTestResult.SrcImageAnchorType)
           {
            AlertDialog.Builder alert = new AlertDialog.Builder(_context);
            alert.SetTitle("Confirm download");
            alert.SetMessage("Do you want to save the picture");
            alert.SetPositiveButton("OK", (senderAlert, args) =>
            {
                //get the pic url
                string picUrl = hitTestResult.Extra;
                //download the pic
                Download(picUrl );

            });
            alert.SetNegativeButton("Cancel", (senderAlert, args) =>
            {
                dialog.Dismiss();
            });
            dialog = alert.Create();
            dialog.Show();
            return true;
        }
        return false;
    }

    private void Download(string picUrl)
      {
            DownloadManager.Request mRequest = new DownloadManager.Request(Android.Net.Uri.Parse(picUrl));
            mRequest.AllowScanningByMediaScanner();
            mRequest.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted);
            DownloadManager mDownloadManager = (DownloadManager)MainActivity.Instance.GetSystemService(Service.DownloadService);
            mDownloadManager.Enqueue(mRequest);
            Toast.MakeText(_context , "Image Downloaded Successfully...", ToastLength.Long).Show();

     }
   }
}

推荐阅读