WebViewの設定

11112 ワード

一、基本配置
1、wb.set WebChromeCient(new WebChromeClient);javascriptをロードするために使用します.
//setWebChromeClient()  
/**
     * Sets the chrome handler. This is an implementation of WebChromeClient for
     * use in handling JavaScript dialogs, favicons, titles, and the progress.
     * This will replace the current handler.
     *
     * @param client an implementation of WebChromeClient
     */
    public void setWebChromeClient(WebChromeClient client) {}
2、wb.set WebView Cient(new WebView Cient)/通知と要求を受信するために、書き換え方法が機能する.
//  :
wb.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (TextUtils.isEmpty(url)) {
                    view.loadUrl(url);//   webview    
                }
                return true;
            }
        });`
//setWebClient()  
/**
     * Sets the WebViewClient that will receive various notifications and
     * requests. This will replace the current handler.
     *
     * @param client an implementation of WebViewClient
     */
    public void setWebViewClient(WebViewClient client) {}
3、WebSettings=wb.get Settings();ws.set JavaScript Enbled(true);/webviewはjsを実行することができます.
4、ws.set Buiilt InZoomControls(false);/ズームボタンを隠す
5、ws.set SaveFormData(false);/フォームデータの保存
6、ws.set Geolocation Enbaled(true);/地理的位置付けを有効にする.
7、ws.setApple Enbled/キャッシュが許可されていますか?
8、ws.setApple CacheMaxSize(1024*10);/キャッシュサイズ設定
9、ws.setUseWideviewPort(true)/任意のスケールでスケーリングできます.
10、ws.setLayout Algorithm(WebSettings.Layout Algorithm.NARROWuCOLUMNS)、可能であれば、すべての列の幅をスクリーンの幅を超えないようにします./ウェブページに各種携帯電話を適応させるために、padは、ウェブページの先端処理を除いて、androidはこちらで処理します.9番目の方法はtrueの場合、適切な方法を設定しなければなりません.
1、Layout Algorithm.NARROWuCOLUMNS:コンテンツサイズ2、Layout Algorithm.SINGLE COLUNMNに適応し、内容は自動的にスケーリングされます.
二、アップロードパラメータ
1、loadUrl(String url, Map<String, String> additionalHttpHeaders);//  header
2、postUrl(String url, byte[] postData)//    
しかし、この二つの方法は同時に使用できません.
//postUrl  
/**
     * Loads the URL with postData using "POST" method into this WebView. If url
     * is not a network URL, it will be loaded with {@link #loadUrl(String)}
     * instead, ignoring the postData param.
     *
     * @param url the URL of the resource to load
     * @param postData the data will be passed to "POST" request, which must be
     *     be "application/x-www-form-urlencoded" encoded.
     */
    public void postUrl(String url, byte[] postData) {
        checkThread();
        if (URLUtil.isNetworkUrl(url)) {
            mProvider.postUrl(url, postData);
        } else {
            mProvider.loadUrl(url);
        }
    }
//loadUrl  
/**
     * Loads the given URL with the specified additional HTTP headers.
     *
     * @param url the URL of the resource to load
     * @param additionalHttpHeaders the additional headers to be used in the
     *            HTTP request for this URL, specified as a map from name to
     *            value. Note that if this map contains any of the headers
     *            that are set by default by this WebView, such as those
     *            controlling caching, accept types or the User-Agent, their
     *            values may be overriden by this WebView's defaults.
     */
    public void loadUrl(String url, Map additionalHttpHeaders) {
        checkThread();
        mProvider.loadUrl(url, additionalHttpHeaders);
    }
3、headerを伝えながらパラメータを伝える
webCientを書き換える必要があります
public class CustomWebClient extends WebViewClient {
    String header = "";

    public CustomWebClient(Activity activity) {
        header = Utility.getUserAgent(activity);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        String actionId = "";
        String path = request.getUrl().toString();
        if (path.contains(Constants.mPrefix_clocks)) {
            actionId = getValueByName(path, "action");//Uri.parse(path).getQueryParameter("action");
            String mParams = "";
            try {
                URL mUrl = new URL(path);
                HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//application/Json; charset=UTF-8
                connection.setRequestProperty("User-Agent", Constants.USER_AGENT_PREFIX + header);
//                connection.setRequestProperty("actionid",  URLEncoder.encode(actionId);//   
//                connection.setRequestProperty("secretString", URLEncoder.encode(secretString));//   
                mParams = "actionid=" + URLEncoder.encode(actionId) + "&secretString=" + URLEncoder.encode(RequestParams.encryptStr1(actionId));
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);
                //     ,    URL    
                DataOutputStream os = new DataOutputStream(connection.getOutputStream());//getoutputstream    
                os.writeBytes(mParams);
                os.flush();
                os.close();
                return new WebResourceResponse("text/html", connection.getContentEncoding(), connection.getInputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }
    }
//そして:webview.loadUrl;
三、webviewキャッシュについて
@Override
protected void onDestroy() {
    super.onDestroy();
    //    Cookie
    CookieSyncManager.createInstance(QzmobileApp.getContext());  //Create a singleton CookieSyncManager within a context
    CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
    cookieManager.removeAllCookie();// Removes all cookies.
    CookieSyncManager.getInstance().sync(); // forces sync manager to sync now

    webView.setWebChromeClient(null);
    webView.setWebViewClient(null);
    webView.getSettings().setJavaScriptEnabled(false);
    webView.clearCache(true);
}
四、コンテント-Typeについてはまだ続きます.
参考:http://blog.csdn.net/liwei123liwei123/article/details/52624826 http://blog.csdn.net/u014473112/article/details/52176412 http://blog.csdn.net/mygoon/article/details/48546781 http://blog.csdn.net/u014473112/article/details/52176412