涉及到不同版本的API的兼容性问题,openFileChooser需要实现以下:
// 添加事件
mWebView.setWebChromeClient(new WebChromeClient() {
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadFile) {
uploadFile(uploadFile);
}
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadFile,
String acceptType) {
uploadFile(uploadFile);
}
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadFile,
String acceptType, String capture) {
uploadFile(uploadFile);
}
});
// 上传文件
private ValueCallback<Uri> mUploadMessage;
private void uploadFile(ValueCallback<Uri> uploadFile) {
mUploadMessage = uploadFile;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"),
FILE_CHOOSER_CODE);
}
// 结果回传
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_CHOOSER_CODE) {
if (mUploadMessage == null)
return;
if (data != null && resultCode == RESULT_OK) {
Uri result = data.getData();
if (result != null) {
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
}
以上是文件上传的过程,重写不同版本的openFileChooser实现上传,然后在onActivityResult中
onReceiveValue将结果回馈给 Js端。以下是混淆相关:
1)为了避免Js调用在混淆后失效,需要添加以下混淆(将Js调用类保持不混淆)
-keepclassmembers class com.umai.taok.manager.JSBridge$AndroidAPI {
public *;
}
-keepclassmembers class com.umai.taok.manager.ClientAPI {
public *;
}
-keep class com.umai.taok.manager.JSBridge$AndroidAPI {
public *;
}
-keep class com.umai.taok.manager.ClientAPI {
public *;
}
-keepattributes *Annotation*
-keepattributes *JavascriptInterface*
2)为了使WebView上传文件能顺利执行,需要添加以下混淆(保持openFileChooser方法不混淆)
-keepclassmembers class * extends android.webkit.WebChromeClient {
public void openFileChooser(...);
}
关于文件上传只执行第一次解决办法
经实验得知,关于openFileChooser上传文件只执行第一次问题,引起的原因是在文件第二次选择返回结果后,或者在选择文件取消操作之后,不能有效的向Js传递结果。所以对应的解决办法就是:
1)在传递对象为空时,将null的结果传递到Js端
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
2)在onActivityResult中判断取消动作,并将null结果传递到Js端
if (resultCode == 0) {
// 取消
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
}