我目前正在使用Xamarin构建一个跨平台的移动的应用程序。
基本上我的应用程序只使用webview(* webview只打开一个网站,有上传图像功能 *),对于一些提取功能,我必须使用webchromeclient为Android。
添加设置webchromeclient后,webview无法从android设备打开文件选取器。(iPhone工作正常,因为webchromeclient与IOS路径无关);
下面是我的项目的结构
---test
|_ CustomWebView.cs
|_ MainPage.xaml
|_ MainPage.cs
---test.Android
|_ MainActivity.cs
|_ AndroidCustomWebViewRenderer.cs
---test.IOS
|_ IOS files
CustomWebView.cs
using Xamarin.Forms;
namespace test
{
public class CustomWebView : WebView
{
}
}
AndroidCustomWebViewRenderer.cs
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
public class CustomWebViewRenderer : WebViewRenderer
{
public CustomWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (this.Control != null)
{
Android.Webkit.WebView webView = this.Control;
webView.Settings.SetGeolocationEnabled(true);
webView.Settings.JavaScriptEnabled = true;
webView.Settings.AllowFileAccess = true;
webView.Settings.AllowFileAccessFromFileURLs = true;
webView.Settings.AllowUniversalAccessFromFileURLs = true;
webView.SetWebChromeClient(new TestWebViewClient());
}
}
public class TestWebViewClient : Android.Webkit.WebChromeClient
{
public override bool OnShowFileChooser(Android.Webkit.WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
return base.OnShowFileChooser(webView, filePathCallback, fileChooserParams);
}
public override bool OnConsoleMessage(Android.Webkit.ConsoleMessage consoleMessage)
{
Log.Debug("WebViewConsole", $"{consoleMessage.Message()}");
return base.OnConsoleMessage(consoleMessage);
}
}
}
MainActivity.cs
namespace test.Droid
{
[Activity(Label = "test", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
AndroidManifest.xml具有访问存储的所有权限。所以我假设webchromeclient有什么问题,从Android打开默认文件选择器时丢失了一些东西。
1条答案
按热度按时间oyxsuwqo1#
您可以尝试将以下代码添加到TestWebViewClient中:
在MainActivity中: