webView加载H5页面,H5调用android本地文件管理器搜索指定类型文件选择并上传
效果图:
?
贴代码:
mWebView.webChromeClient = object : WebChromeClient() {
val mIsLoadFinish : AtomicBoolean = AtomicBoolean(false)
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?): Boolean {
uploadMessageAboveL = filePathCallback
PermissionX.init(this@WebActivity)
.permissions( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
.request(RequestCallback { allGranted, grantedList, deniedList ->
if (allGranted) {
val acceptTypes = fileChooserParams!!.acceptTypes
startActivityForResult(Intent.createChooser(getFilerChooserIntent(acceptTypes[0]), "File Chooser"), CHOOSER_REQUEST_OA)
} else {
ToastManager.show("此功能需要存储权限,请在设置-应用中开启!")
}
})
return true
}
fun getFilerChooserIntent(flag : String) : Intent{
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
intent.addCategory(Intent.CATEGORY_OPENABLE)
when(flag){
".jpg"->{
intent.type = "image/*"
}
".xls"->{
intent.putExtra(Intent.EXTRA_MIME_TYPES, arrayOf(MimeTyppes.XLS, MimeTyppes.XLST, MimeTyppes.XLSX))
intent.type = "*/*"
}
".pdf"->{
intent.type = "application/pdf"
}
".doc"->{
intent.putExtra(Intent.EXTRA_MIME_TYPES, arrayOf(MimeTyppes.DOC, MimeTyppes.DOCX, MimeTyppes.DOTX))
intent.type = "*/*"
}
else->{
intent.type = "*/*"
}
}
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
return intent
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == CHOOSER_REQUEST_OA){
if ( null == uploadMessageAboveL) return
if (uploadMessageAboveL != null) {
onActivityResultAboveLOA(requestCode, resultCode, data)
}
}
}
private fun onActivityResultAboveLOA(requestCode: Int, resultCode: Int, intent: Intent?) {
if ( uploadMessageAboveL == null) return
var results: Array<Uri>? = null
if (resultCode == RESULT_OK) {
if (intent != null) {
val dataString = intent.dataString
if (dataString != null) results = arrayOf(Uri.parse(dataString))
}
}
uploadMessageAboveL!!.onReceiveValue(results)
uploadMessageAboveL = null
}
object MimeTyppes {
val DOC = "application/msword"
val DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
val DOTX = "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
val XLS = "application/vnd.ms-excel"
val XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
val XLST = "application/vnd.openxmlformats-officedocument.spreadsheetml.template"
val PDF = "application/pdf"
}
|