Fiaz Ahmed Ranjha
Fiaz Ahmed Ranjha

Reputation: 253

Xamarin.Android webview does not open the file, but file upload works fine (need C# code)

I have WebView which works fine for file upload but when I click on files to open or download, nothing happens. but in normal browser when I click on file it is opened successfully. the intention of code is to open the file when it is clicked. file choose chrome extension is fine. I think there is need to add some code in WebViewListner block.

The activity code is here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Net;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;

namespace smartbookapp
{
    [Activity(Label = "JobActivity")]
    public class JobActivity : Activity
    {

        public WebView webview;
        public IValueCallback mUploadMessage;
        public static ProgressBar progressBar;
        public static int FILECHOOSER_RESULTCODE = 1;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Jobs);

            webview = FindViewById<WebView>(Resource.Id.JobView);
            // show progress bar
            progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
            //

            webview.Settings.JavaScriptEnabled = true;
            webview.Settings.SetAppCacheEnabled(true);
            webview.Settings.AllowFileAccess = true;
            webview.Settings.BuiltInZoomControls = true;
            webview.SetWebViewClient(new WebViewListener());

            webview.SetWebChromeClient(new JobWebChromeClient(this));
            webview.LoadUrl("https://smartbook.pk/Jobs/index");

            //
        }



        //
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {

            if (requestCode == FILECHOOSER_RESULTCODE)
            {
                if (null == mUploadMessage) return;
                Android.Net.Uri[] result = data == null || resultCode != Result.Ok ? null : new Android.Net.Uri[] { data.Data };
                try
                {
                    mUploadMessage.OnReceiveValue(result);

                }
#pragma warning disable CS0168 // Variable is declared but never used
                catch (Exception e)
#pragma warning restore CS0168 // Variable is declared but never used
                {
                }

                mUploadMessage = null;
            }
            base.OnActivityResult(requestCode, resultCode, data);
        }
        // webview listener code here
        public class WebViewListener : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
            {
                view.LoadUrl(request.Url.ToString());
                return true;
            }
            public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
            {

                progressBar.Progress = view.Progress;
            }
            public override void OnLoadResource(WebView view, string url)
            {

                progressBar.Progress = view.Progress;
            }
            public override void OnPageFinished(WebView view, string url)
            {

                progressBar.Progress = 0;
            }
        }
        public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
        {
            if (keyCode == Keycode.Back && webview.CanGoBack())
            {
                webview.GoBack();

                return true;
            }

            return base.OnKeyDown(keyCode, e);
        }
    }

    // download files from webview

    public class JobWebChromeClient : WebChromeClient
    {

        JobActivity WebViewActivity;
        public JobWebChromeClient(JobActivity activity)
        {
            WebViewActivity = activity;

        }
        public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
        {
            WebViewActivity.mUploadMessage = filePathCallback;
            Intent i = new Intent(Intent.ActionGetContent);
            i.AddCategory(Intent.CategoryOpenable);
            i.SetType("*/*");
            WebViewActivity.StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), JobActivity.FILECHOOSER_RESULTCODE);

            return true;
        }

    }

}

enter image description here

Upvotes: 1

Views: 670

Answers (1)

Leon Lu
Leon Lu

Reputation: 9234

First of all, make sure your WebView has enabled javascript and the WebViewClient is set correctly.

WebView mWebview = FindViewById<WebView>(Resource.Id.webView1);
mWebview.Download += MWebview_Download;
var client = new WebViewClient();
mWebview.Settings.JavaScriptEnabled = true;
mWebview.SetWebViewClient(client);
mWebview.LoadUrl("your url");

Then, we shouldd achieve WebView.Download event(use DownloadManager to download the file)

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

request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted); //Notify client once download is completed!
request.SetDestinationInExternalPublicDir(Environment.DirectoryDownloads, "CPPPrimer");
DownloadManager dm = (DownloadManager)GetSystemService("download");
dm.Enqueue(request);
Toast.MakeText(ApplicationContext, "Downloading File",ToastLength.Long//To notify the Client that the file is being downloaded
            ).Show();
}

Upvotes: 1

Related Questions