由于本应用版本较低 未写Android7.0以上权限适配和文件读取适配;
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.setWebChromeClient(new MyWebChromeClient());
WebViewUtils..WebViewSetting(mWebView);
新建WebViewUtils类:
public static void WebViewSetting(WebView webView) {
webView.canGoForward();
webView.canGoBack();
/* //支持javascript
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
// 设置可以支持缩放webView.getSettings().setSupportZoom(true);
// 设置出现缩放工具webView.getSettings().setBuiltInZoomControls(true);
//扩大比例的缩放webView.getSettings().setUseWideViewPort(true);
//自适应屏幕*/
WebSettings webSetting = webView.getSettings();
webSetting.setAllowFileAccess(true);
webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSetting.setSupportZoom(false);
webSetting.setBuiltInZoomControls(false);
webSetting.setUseWideViewPort(true);
webSetting.setSupportMultipleWindows(false);//这里一定得是false,不然打开的网页中,不能在点击打开了
// webSetting.setLoadWithOverviewMode(true);
webSetting.setAppCacheEnabled(true);
// webSetting.setDatabaseEnabled(true);
webSetting.setDomStorageEnabled(true);
webSetting.setJavaScriptEnabled(true);
webSetting.setGeolocationEnabled(true);
webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
// webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
// webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
// webSetting.setPreFectch(true);
// this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extensio
// webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webSetting.setLoadWithOverviewMode(true);
String ua = webView.getSettings().getUserAgentString();
webView.getSettings().setUserAgentString(ua.replace("Android", "HFWSH_USER_Android"));
if (webView.getX5WebViewExtension() !=null) {
//开启X5全屏播放模式
Bundle data =new Bundle();
data.putBoolean("standardFullScreen", false);// true表示标准全屏,false表示X5全屏;不设置默认false,
data.putBoolean("supportLiteWnd", true);// false:关闭小窗;true:开启小窗;不设置默认true,
data.putInt("DefaultVideoScreen", 2);// 1:以页面内开始播放,2:以全屏开始播放;不设置默认:1
webView.getX5WebViewExtension().invokeMiscMethod("setVideoParams",
data);
}
}
在Activity中自定义WebViewClient
private class MyWebViewClient extends WebViewClient {
final Dialogdialog = DialogUtils.createLoadingDialog(context, "加载中...");
public MyWebViewClient() {
super();
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (URLUtil.isNetworkUrl(url)) {
final ConnectionQuality connectionQuality = ConnectionClassManager.getInstance().getCurrentBandwidthQuality();
String name = connectionQuality.name();
if (name.equals("POOR")) {
Toast.makeText(context, "当前网络差", Toast.LENGTH_SHORT).show();
}
view.loadUrl(url);
}else {
Toast.makeText(context, "链接无效", Toast.LENGTH_SHORT).show();
// context.finish();
}
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (dialog !=null) {
dialog.show();
}
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
DialogUtils.closeDialog(dialog);
DeviceBandwidthSampler.getInstance().stopSampling();
}
}
在Activity中自定义WebChromeClient
private class MyWebChromeClient extends WebChromeClient {
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
Log.d(TAG, "openFileChooser");
if (mUploadMessage !=null)return;
mUploadMessage = uploadMsg;
selectImage();
}
// For Android < 3.0
public void openFileChooser(ValueCallback uploadMsg) {
openFileChooser(uploadMsg, "");
}
// For Android > 4.1.1
public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
// For Android 5.0
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
if (mUploadMessagesAboveL !=null) {
mUploadMessagesAboveL.onReceiveValue(null);
}else {
mUploadMessagesAboveL = filePathCallback;
selectImage();
}
return true;
}
}
在Activity中调用
常量声明:
private static final StringTAG ="MainActivity";
private static final int REQUEST_CAMERA =1;
private static final int REQUEST_CHOOSE =2;
ValueCallbackmUploadMessage;
ValueCallbackmUploadMessagesAboveL;
private UricameraUri;
/**
* 打开照相机
*/
private void openCarcme() {
Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String imagePaths = Environment.getExternalStorageDirectory().getPath() +"/yicaitong/Images/" + (System.currentTimeMillis() +".jpg");
// 必须确保文件夹路径存在,否则拍照后无法完成回调
File vFile =new File(imagePaths);
if (!vFile.exists()) {
File vDirPath = vFile.getParentFile();
vDirPath.mkdirs();
}else {
if (vFile.exists()) {
vFile.delete();
}
}
cameraUri = Uri.fromFile(vFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
/**
* 本地相册选择图片
*/
private void chosePicture() {
Intent innerIntent =new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
innerIntent.setType("image/*");
Intent wrapperIntent = Intent.createChooser(innerIntent, null);
startActivityForResult(wrapperIntent, REQUEST_CHOOSE);
}
/**
* 选择照片后结束
*
* @param data
*/
private UriafterChosePic(Intent data) {
if (data !=null) {
final String path = data.getData().getPath();
if (path !=null && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG"))) {
return data.getData();
}else {
Toast.makeText(this, "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT).show();
}
}
return null;
}
private void selectImage() {
if (!FileUtils.checkSDcard(this)) {
return;
}
String[] selectPicTypeStr = {"拍照", "图库"};
new AlertDialog.Builder(this)
.setOnCancelListener(new ReOnCancelListener())
.setItems(selectPicTypeStr,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
// 相机拍摄
case 0:
openCarcme();
break;
// 手机相册
case 1:
chosePicture();
break;
}
}
}).show();
}
/**
* 返回文件选择
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (mUploadMessagesAboveL !=null) {
onActivityResultAboveL(requestCode, resultCode, intent);
}
if (mUploadMessage ==null)return;
Uri uri =null;
if (requestCode ==REQUEST_CAMERA && resultCode ==RESULT_OK) {
uri =cameraUri;
Log.e("onActivityResult: ", uri.toString());
}
if (requestCode ==REQUEST_CHOOSE && resultCode ==RESULT_OK) {
uri = afterChosePic(intent);
}
mUploadMessage.onReceiveValue(uri);
mUploadMessage =null;
super.onActivityResult(requestCode, resultCode, intent);
}
/**
* 5.0以后机型 返回文件选择
*
* @param requestCode
* @param resultCode
* @param data
*/
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
Uri[] results =null;
if (requestCode ==REQUEST_CAMERA && resultCode ==RESULT_OK) {
results =new Uri[]{cameraUri};
}
if (requestCode ==REQUEST_CHOOSE && resultCode ==RESULT_OK) {
if (data !=null) {
String dataString = data.getDataString();
if (dataString !=null)
results =new Uri[]{Uri.parse(dataString)};
}
}
mUploadMessagesAboveL.onReceiveValue(results);
mUploadMessagesAboveL =null;
return;
}
/**
* dialog监听类
*/
private class ReOnCancelListenerimplements DialogInterface.OnCancelListener {
@Override
public void onCancel(DialogInterface dialogInterface) {
if (mUploadMessage !=null) {
mUploadMessage.onReceiveValue(null);
mUploadMessage =null;
}
if (mUploadMessagesAboveL !=null) {
mUploadMessagesAboveL.onReceiveValue(null);
mUploadMessagesAboveL =null;
}
}
}