Min SDK API 15
Run Code Online (Sandbox Code Playgroud)
你好,
我使用的webview上有一个按钮,可以浏览应用程序照片库.
但是,在webview中单击按钮时,没有任何反应.
网址格式为:
https://www.xxxxxxxxxxx
Run Code Online (Sandbox Code Playgroud)
我添加了以下权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
Run Code Online (Sandbox Code Playgroud)
我有一个片段,它将在启用了javascript的onCreateView方法(仅限代码段)中加载webview.
if(!message.isEmpty()) {
WebView webView = (WebView)view.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(message);
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个简单的html页面来测试:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test Android Popup</title>
</head>
<body>
<label>Test Alert 1:</label>
<button type="button" onClick="alert('Test Alert Box1');">Click Me!</button>
<br>
<label>Test Browse file</label>
<input type="file" name="img">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
所以url将被加载到webview中.webview显示一个按钮,用户将单击该按钮浏览其库中的照片.
webview看起来像这样:

单击它们时,所有按钮都不起作用.
非常感谢任何建议,
此代码段适用于<4.3.但是,4.4和5.0失败了.
webView.setWebChromeClient(new WebChromeClient() {
/* Open File */
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mImageFilePath = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, FILECHOOSER_RESULTCODE);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mImageFilePath = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, FILECHOOSER_RESULTCODE);
}
});
Run Code Online (Sandbox Code Playgroud)
创建此文件并将其放在您的资源文件夹中:webdemo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>title</title>
</head>
<body>
<h1>Web View Demo</h1>
<br>
<input type="button" value="Say hello"
onClick="showAndroidToast('Hello Android!')" />
<br />
File Uri: <label id="lbluri">no file uri</label>
<br />
File Path: <label id="lblpath">no file path</label>
<br />
<input type="button" value="Choose Photo" onClick="choosePhoto()" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
function setFilePath(file) {
document.getElementById('lblpath').innerHTML = file;
Android.showToast(file);
}
function setFileUri(uri) {
document.getElementById('lbluri').innerHTML = uri;
Android.showToast(uri);
}
function choosePhoto() {
var file = Android.choosePhoto();
window.alert("file = " + file);
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
专注于这里写的javascript.
编写您的活动如下: WebViewDemo.java
public class WebViewDemo extends Activity
{
private WebView webView;
final int SELECT_PHOTO = 1;
@SuppressLint("SetJavaScriptEnabled")
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.show_web_view);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
// Other webview settings
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
webView.addJavascriptInterface(new MyJavascriptInterface(this), "Android");
webView.loadUrl("file:///android_asset/webdemo.html");
}
class MyJavascriptInterface
{
Context mContext;
/** Instantiate the interface and set the context */
MyJavascriptInterface(Context c)
{
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast)
{
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public String choosePhoto()
{
// TODO Auto-generated method stub
String file = "test";
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
return file;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
switch (requestCode)
{
case SELECT_PHOTO:
if (resultCode == RESULT_OK)
{
Uri selectedImage = intent.getData();
webView.loadUrl("javascript:setFileUri('" + selectedImage.toString() + "')");
String path = getRealPathFromURI(this, selectedImage);
webView.loadUrl("javascript:setFilePath('" + path + "')");
}
}
}
public String getRealPathFromURI(Context context, Uri contentUri)
{
Cursor cursor = null;
try
{
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用此代码段并查看它是否有效.
以下截图取自Android 4.4 Kitkat设备.

我不知道这个解决方案是否有效.对您而言,这可能只是一种解决方法或突破.我希望它的某些部分会有所帮助.
不幸的是,正如用户Slartibartfast在您的问题的一条评论中所说,输入类型"文件"不适用于4.4设备.Google代码存在一个问题,即此操作是预期的行为(状态:WorkingAsIntended).
即便如此,您提供的代码也适用于4.4.4(在Nexus 7平板电脑上测试)和<4.4 os版本.
在5.0上,他们添加了一个记录的方法来执行此操作.我正在使用以下代码:
mWebView.setWebChromeClient(new WebChromeClient() {
// For Android < 3.0 - undocumented method
@SuppressWarnings("unused")
public void openFileChooser( ValueCallback<Uri> uploadMsg ) {
openFileChooser( uploadMsg, "" );
}
// For Android 3.0+ - undocumented method
public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) {
mUploadCallback = uploadMsg;
openFileChooserActivity();
}
// For Android > 4.1 - undocumented method
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
openFileChooser( uploadMsg, "" );
}
// For Android > 5.0
public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mUploadCallbackLollipop = filePathCallback;
openFileChooserActivity();
return true;
}
});
Run Code Online (Sandbox Code Playgroud)
请注意> 5.0的已更改回调参数:从.ValueCallback<Uri>到ValueCallback<Uri[]>.
因此,对于> = 4.4和<4.4.4,您应该实现自己的文件上传机制.一些建议:
<input type="file">它的工作原理.在4.4版本中,使用您自己的url架构创建一个html元素(例如,Sushant说<form action="image://choose">).然后你可以捕获它shouldOverrideUrlLoading并使用文件路径从java调用javascript函数,但是你将无法访问文件的内容.对于小文件,您可以将base64中的文件内容作为参数传递给javascript函数,但对于较大的文件,您肯定会获得OutOfMemory异常.因此,作为结论,我看到了4.4和4.4.4之间的os版本的两个选项:使用javascript上传文件(内存问题)或者在java中上传它并在你的应用程序和webview之间实现你自己的通信机制.对于他们两个,您需要访问您在webview中加载的网页.
我使用了javascript上传方法,因为我们使用的是小文件,实现起来要快一些:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
... else if (url.startsWith(UPLOAD_FILE_URL_PREFIX)) {
openFileChooserActivity();
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
在活动结果上,我为4.4版本做了类似的事情(javascript函数insertFileForUpload处理文件上传):
private void invokeJavascriptWithFileContent(Uri fileUri) {
String fileContentInBase64 = readAndConvertFileToBase64(fileUri);
if (!fileContentInBase64.isEmpty()) {
String fileMimeType = getMimeType(activity, fileUri);
String fileName = getFileName(activity, fileUri);
// invoke javascript
String js = String.format("javascript:insertFileForUpload(\"%s\",\"%s\",\"%s\")",
fileName,
fileMimeType,
fileContentInBase64
);
mWebView.loadUrl(js);
}
}
public static String getMimeType(Context context, Uri fileUri)
{
ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getExtensionFromMimeType(cR.getType(fileUri));
return type;
}
Run Code Online (Sandbox Code Playgroud)
此外,关于https://github.com/delight-im/Android-AdvancedWebView,似乎文件上传工作,但他们说:'文件上传自动处理(检查可用性与AdvancedWebView.isFileUploadAvailable())'和'isFileUploadAvailable '包含以下代码:
/**
* Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4)
*
* @return whether file uploads can be used
*/
public static boolean isFileUploadAvailable() {
return isFileUploadAvailable(false);
}
/**
* Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4)
*
* On Android 4.4.3/4.4.4, file uploads may be possible but will come with a wrong MIME type
*
* @param needsCorrectMimeType whether a correct MIME type is required for file uploads or `application/octet-stream` is acceptable
* @return whether file uploads can be used
*/
public static boolean isFileUploadAvailable(final boolean needsCorrectMimeType) {
if (Build.VERSION.SDK_INT == 19) {
final String platformVersion = (Build.VERSION.RELEASE == null) ? "" : Build.VERSION.RELEASE;
return !needsCorrectMimeType && (platformVersion.startsWith("4.4.3") || platformVersion.startsWith("4.4.4"));
}
else {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
所以你可能会遇到与普通webview相同的问题,但我还没有测试过库,所以我真的不能说.
我可能已经创造了一个混乱的答案,但我希望你能找到一些有用的东西.
| 归档时间: |
|
| 查看次数: |
17605 次 |
| 最近记录: |