Android中WebView的设置与使用

1、WebSettings的设置:

     介绍websettings的常用的一些

WebSettings settings = webview.getSettings();
  settings .setRenderPriority(WebSettings.RenderPriority.HIGH);
  //开启本地DOM存储
  settings.setDomStorageEnabled(true);
  settings.setUseWideViewPort(true);
  settings.setLoadWithOverviewMode(true);
  // 是否可访问Content Provider的资源,默认值 true
  settings.setAllowContentAccess(true);
  // 是否可访问本地文件,默认值 true
  settings.setAllowFileAccess(true);
  // 是否允许通过file url加载的Javascript读取本地文件,默认值 false
  settings.setAllowFileAccessFromFileURLs(false);
  // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https),默认值 false
  settings.setAllowUniversalAccessFromFileURLs(false);
  settings.setJavaScriptEnabled(true);
  settings.setSupportZoom(true);

2、WebViewClient的设置:

     

webview.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        view.loadUrl(url);
        return super.shouldOverrideUrlLoading(view, url);
    }
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
    }
});
 

3、WebChromeClient的设置

这里只是进行一汇总一些自己用到的以及常用的设置

此为打开手机本地内存时调用的方法:

webview.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onShowFileChooser(WebView webView,
                                     ValueCallback filePathCallback,
                                     FileChooserParams fileChooserParams) {
        mUploadCallbackAboveL = filePathCallback;
        takeSDstorage();
        return true;
    }

    public void openFileChooser(ValueCallback uploadMsg) {
        mUploadMessage = uploadMsg;
        takeSDstorage();
    }

    public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
        mUploadMessage = uploadMsg;
        takeSDstorage();
    }

    public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
        mUploadMessage = uploadMsg;
        takeSDstorage();
    }
});
 

其他常用的拦截设置

/**

* 当网页调用alert()来弹出alert弹出框前回调,用以拦截alert()函数

*/

public boolean onJsAlert(WebView view, String url, String message,JsResult result)

/**

* 当网页调用confirm()来弹出confirm弹出框前回调,用以拦截confirm()函数

*/

public boolean onJsConfirm(WebView view, String url, String message,JsResult result)

/**

* 当网页调用prompt()来弹出prompt弹出框前回调,用以拦截prompt()函数

*/

public boolean onJsPrompt(WebView view, String url, String message,String defaultValue, JsPromptResult result)

/**

* 打印 console 信息

*/

public boolean onConsoleMessage(ConsoleMessage consoleMessage)

/**

* 通知程序当前页面加载进度

*/

public void onProgressChanged(WebView view, int newProgress)

4、调取本地内存,选取索要上传的文件

   全局变量定义:

    /**
     * 表单的数据信息
     */
    private ValueCallback mUploadMessage;
    private ValueCallback mUploadCallbackAboveL;
    /**
     * 表单的结果回调
     */
    private final static int FILECHOOSER_RESULTCODE = 1;
    private Uri imageUri;
    File file;

  方法:

private void takeSDstorage() {
    File imageStorageDir = new            File(Environment.getExternalStoragePublicDirectory(Environment.getExternalStorageState()), "MyApp");
    // Create the storage directory if it does not exist
    if (!imageStorageDir.exists()) {
        imageStorageDir.mkdirs();
    }
    imageUri = Uri.fromFile(imageStorageDir);

    final List cameraIntents = new ArrayList();
    final Intent captureIntent = new Intent(MediaStore.AUTHORITY);
    final PackageManager packageManager = getPackageManager();
    final List listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for (ResolveInfo res : listCam) {
        final String packageName = res.activityInfo.packageName;
        final Intent i = new Intent(captureIntent);
        i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        i.setPackage(packageName);
        i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        cameraIntents.add(i);

    }
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.addCategory(Intent.CATEGORY_OPENABLE);
    i.setDataAndType(imageUri, MapTable.getMIMEType(imageStorageDir.getName()));
    Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
    WebviewSummaryActivity.this.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
 

5、选取好本地文件后进行上传时的回调

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage && null == mUploadCallbackAboveL) {
            return;
        }
        Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
        if (mUploadCallbackAboveL != null) {
            onActivityResultAboveL(requestCode, resultCode, data);
        } else if (mUploadMessage != null) {
            Log.e("result", result + "");
            if (result == null) {
                mUploadMessage.onReceiveValue(imageUri);
                mUploadMessage = null;

                Log.e("imageUri", imageUri + "");
            } else {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }


        }
    }
}


@SuppressWarnings("null")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
    if (requestCode != FILECHOOSER_RESULTCODE
            || mUploadCallbackAboveL == null) {
        return;
    }

    Uri[] results = null;
    if (resultCode == Activity.RESULT_OK) {
        if (data == null) {
            results = new Uri[]{imageUri};
        } else {
            String dataString = data.getDataString();
            ClipData clipData = data.getClipData();

            if (clipData != null) {
                results = new Uri[clipData.getItemCount()];
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item item = clipData.getItemAt(i);
                    results[i] = item.getUri();
                }
            }

            if (dataString != null) {
                results = new Uri[]{Uri.parse(dataString)};
            }
        }
    }
    if (results != null) {
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
    } else {
        results = new Uri[]{imageUri};
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
    }

    return;
}
 

6、H5页面调用原生方法:

本地方法:

class JavaScriptInterfaces {
    JavaScriptInterfaces() {
    }

    @JavascriptInterface
    public void backUpperLevel() {
        webView.loadUrl(url);
    }
}

@JavascriptInterface注释必须添加,

初始化时添加:

webView.addJavascriptInterface(new JavaScriptInterfaces(), "android");

参数一:具体的对象,也就是H5与Android交互的实体类

参数二:参数一对象的实例化对象,也就是给前端调用的类名

 

本文主要是以自己所用要的WebView时所用到的进行汇总记录

你可能感兴趣的:(常用功能总结)