mauimaui-android

Download files in MAUI Android WebView


I have a WebView in a MAUI app that generally works, but whenever I click a link on Android that is supposed to download a file (link returns a Content-Disposition header) nothing happens.

How is this supposed to be implemented? I can't find any documentation.

<WebView
    x:Name="WebView"
    Source=".." />
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    protected override bool OnBackButtonPressed()
    {
        base.OnBackButtonPressed();

        if (WebView.CanGoBack)
        {
            WebView.GoBack();
            return true;
        }
        else
        {
            base.OnBackButtonPressed();
            return true;
        }
    }
}

Related question for iOS: Download files in MAUI iOS WebView


Solution

  • For the android, you can try to add a DownloadListener to the webview. I have testd it and the file can download successfully.

    Create the custom downloadlistener class in the \Platforms\Android:

        public class MyDownLoadListener : Java.Lang.Object, IDownloadListener
        {
            public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
            {
                var manager = (DownloadManager)Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.GetSystemService(global::Android.App.Application.DownloadService);
                var uri = global::Android.Net.Uri.Parse(url);
                DownloadManager.Request downloadrequest = new DownloadManager.Request(uri);
                downloadrequest.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
                manager.Enqueue(downloadrequest);
            }
        }
    

    In the page's xaml:

     <WebView x:Name="webview" Source="https://www.myfreemp3.com.cn/" HeightRequest="500"/>
    

    And set the listener for the webview in the Page.cs:

       protected override void OnHandlerChanged()
        {
            base.OnHandlerChanged();
    #if ANDROID
            (webview.Handler.PlatformView as Android.Webkit.WebView).SetDownloadListener(new Platforms.Android.MyDownLoadListener());
            (webview.Handler.PlatformView as Android.Webkit.WebView).Settings.JavaScriptEnabled = true;
            (webview.Handler.PlatformView as Android.Webkit.WebView).Settings.DomStorageEnabled = true;
    #endif
        }