WebView选择发送图片和拨打电话功能
需求:app内有一个联系客服界面,界面内有发送图片和拨打电话功能,在电脑上是没有问题的,所以需要app自行在webview上做处理
1.首先要设置webview支持javascript
//设置WebView属性,能够执行Javascript脚本
webSettings.setJavaScriptEnabled(true);
//设置可以访问文件
webSettings.setAllowFileAccess(true);
2.调用拨打电话功能,重写WebViewClient
webview.setWebViewClient(new MyWebViewClient());
//Web视图
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} else {
view.loadUrl(url);
}
return true;
}
}
3.选择图片并且发送,重写WebChromeClient
private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
private ValueCallback<Uri[]> mUploadFilePath;
private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调
//加载进度条和标题以及发送图片
webview.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
webview_progress.setProgress(newProgress);
LogUtils.i("Loading... newProgress:" + newProgress);
if (newProgress == 100)
webview_progress.setVisibility(View.GONE);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
if (!TextUtils.isEmpty(title)) {
titleBar.setTitle(title);
}
}
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
take();
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
take();
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
take();
}
//Android 5.0+
@Override
@SuppressLint("NewApi")
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
if (mUploadFilePath != null) {
mUploadFilePath.onReceiveValue(null);
}
LogUtils.i("file chooser params:" + fileChooserParams.toString());
mUploadFilePath = filePathCallback;
take();
return true;
}
});
private void take() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "选择图片"), FILECHOOSER_RESULTCODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (FILECHOOSER_RESULTCODE == requestCode) {
if (null == mUploadMessage && mUploadFilePath == null) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(result);
} else if (mUploadFilePath != null && result != null) {
mUploadFilePath.onReceiveValue(new Uri[]{result});
}else if(mUploadMessage!=null){
mUploadMessage.onReceiveValue(null);
}else if(mUploadFilePath!=null){
mUploadFilePath.onReceiveValue(null);
}
//嗯,一定要置为null
mUploadMessage = null;
mUploadFilePath = null;
return;
}
好啦,大功告成