我使用下面的代码打开文件选择器,我不确定如何在 Android 5.0 及更高版本上实现它。
Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback;
public FileChooserWebChromeClient(Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback)
{
this.callback = callback;
}
//For Android 4.1
[Java.Interop.Export]
public void openFileChooser(IValueCallback uploadMsg, Java.Lang.String acceptType, Java.Lang.String capture)
{
callback(uploadMsg, acceptType, capture);
}
// For Android > 5.0
//I am stuck here, taken from Android
[Java.Interop.Export]
public bool onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
mUploadCallbackLollipop = filePathCallback;
openFileChooserActivity();
return true;
}
回调函数:
var chrome = new FileChooserWebChromeClient((uploadMsg, acceptType, capture) =>
{
MainActivity.UploadMessage = uploadMsg;
if(Build.VERSION.SdkInt < BuildVersionCodes.Kitkat)
{
var i = new Intent(Intent.ActionGetContent);
//To set all type of files
i.SetType("image/*");
//Here File Chooser dialog is started as Activity, and it gives result while coming back from that Activity.
((MainActivity)this.Context).StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), MainActivity.GALLERY_INTENT_CALLED);
}
else
{
var i = new Intent(Intent.ActionOpenDocument);
i.AddCategory(Intent.CategoryOpenable);
//To set all type of files
i.SetType("image/*");
//Here File Chooser dialog is started as Activity, and it gives result while coming back from that Activity.
((MainActivity)this.Context).StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), MainActivity.GALLERY_KITKAT_INTENT_CALLED);
}
});
Android 5.0以上版本如何实现回调,请帮忙
最佳答案
以下代码在 Android 5.0 (Lollipop) 的 WebView 中打开文件选择器
// For Android > 5.0
[Android.Runtime.Register("onShowFileChooser", "(Landroid/webkit/WebView;Landroid/webkit/ValueCallback;Landroid/webkit/WebChromeClient$FileChooserParams;)Z", "GetOnShowFileChooser_Landroid_webkit_WebView_Landroid_webkit_ValueCallback_Landroid_webkit_WebChromeClient_FileChooserParams_Handler")]
public override Boolean OnShowFileChooser (Android.Webkit.WebView webView, IValueCallback uploadMsg, WebChromeClient.FileChooserParams fileChooserParams)
{
try
{
callback(uploadMsg, null, null);
}
catch(Exception e)
{
}
return true;
}
回调的实现方式与其他版本相同,但OnReceiveValue
方法中不能直接传递路径。它应该按如下方式传递:
UploadMessage.OnReceiveValue(WebChromeClient.FileChooserParams.ParseResult(Convert.ToInt32(resultCode), intent));
我在使用旧版本中使用的以下函数时遇到类型转换异常。
UploadMessage.OnReceiveValue(Android.Net.Uri.Parse(string.Format("file://{0}", result.ToString())));
引用:
来自 Android 源代码:
关于c# - 如何在Xamarin中实现Android 5.0以上的打开文件选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35341665/