android - 从头开始添加webview

访问量: 104

refer : http://www.cnblogs.com/tinyphp/p/3858997.html

1. android manifest.xml ,添加网络权限:

<uses-permission android:name="android.permission.INTERNET"/>

2. 添加xml:

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </WebView>

3. activity中,添加代码:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = (WebView) findViewById(R.id.webView);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        WebSettings settings = webView.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);    //排版适应屏幕
        settings.setLoadWithOverviewMode(true);                             // setUseWideViewPort方法设置webview推荐使用的窗口。setL
        settings.setUseWideViewPort(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        settings.setDefaultTextEncodingName("UTF-8");

        webView.setWebChromeClient(new WebChromeClient());
        webview.loadUrl("http://siwei.me");    
     }

4. 自定义 web client, 进行url 的拦截。 

(先在 build.gradle中,添加 okhttp
    compile 'com.squareup.okhttp3:okhttp:3.8.1'

然后增加这个class

   
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;

/**
 * new GenericWebViewClient(getApplicationContext().getCacheDir())
 *
 */
public class GenericWebViewClient extends WebViewClient {

    public String TAG = this.getClass().getSimpleName();

    public GenericWebViewClient(File folder){
        this.cacheFolder = folder;
    }

    private File cacheFolder;

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        Log.d(TAG, "onPageStarted, 触发的url是====" + url);
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        Log.d(TAG, "取消小菊花开始...");
        // 取消小菊花 放在这里才可以.   针对myorder  打开的时候小菊花不会消失。
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        Log.d(TAG, "shouldInterceptRequest, 触发的url是====" + url);
        if(url.contains("__webpack_hmr")) {
            Log.d(TAG, "return empty response on __webpack_hmr");
            return new WebResourceResponse(null,null, null);
        }

        if( shouldQueryFromCache(url)) {
            return queryFromCacheIfPossible(url);
        }

        return super.shouldInterceptRequest(view, url);
    }



    public boolean shouldQueryFromCache(String url) {

        // endsWith 方法貌似不支持   a | b 这样的表达式...只好这么写了 ...   Orz
        boolean result =  url.endsWith("png") ||
                url.endsWith("PNG") ||
                url.endsWith("jpg") ||
                url.endsWith("JPG") ||
                url.endsWith("jpeg") ||
                url.endsWith("JPEG") ||
                url.endsWith("css") ||
                url.endsWith("css.map") ||
                url.endsWith("js") ||
                url.endsWith("js.map");

        return result;
    }

    /**
     * 核心方法. 根据url, 向远程发起请求, 并保存文件到本地.
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public WebResourceResponse queryFromCacheIfPossible(final String url) {
        Log.d(TAG, "== in queryFromCacheIfPossible, url: "+ url);

        String webResourceLocalFileName = getWebResourceLocalFileName(url);
        File webResourceCacheFile = new File( cacheFolder, webResourceLocalFileName);

        if(webResourceCacheFile.exists()){
            Log.d(TAG, "== hit the cache: " + webResourceLocalFileName);
            try{
                FileInputStream fileInputStream = new FileInputStream(new File(cacheFolder, webResourceLocalFileName));
                return new WebResourceResponse(getMimeTypeBySuffix(url), "utf-8", fileInputStream);
            }catch (IOException e){
                e.printStackTrace();
                return new WebResourceResponse(getMimeTypeBySuffix(url), "utf-8", null);
            }
        }else{
            Log.d(TAG, "== NOT hit the cache: " + webResourceLocalFileName);
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            try {
                Response response = okHttpClient.newCall(request).execute();

                writeHttpResponseToFile(url, response);
                Log.d(TAG, "== mime : " + getMimeTypeBySuffix(url));
                // 这段代码可以让图片正常显示!
                //   js:  doing...
                FileInputStream fileInputStream = new FileInputStream(new File(cacheFolder, webResourceLocalFileName));

                return new WebResourceResponse(getMimeTypeBySuffix(url), "utf-8", fileInputStream);

            }catch (IOException e){
                Log.e(TAG, "== got IOException");
                e.printStackTrace();
                return new WebResourceResponse(getMimeTypeBySuffix(url), "utf-8", null);
            }
        }

    }

    public String getWebResourceLocalFileName(String url){
        String[] temp = url.split("/");
        String fileName = temp[temp.length - 1];
        return fileName;
    }

    public String writeHttpResponseToFile(String url, Response response){
        String fileName = getWebResourceLocalFileName(url);
        Log.d(TAG, "== in writeHttpResponseToFile");
        // TODO Write file ...
        File file = new File(cacheFolder, fileName);

        try{
            BufferedSink bufferedSink = Okio.buffer(Okio.sink(file));
            bufferedSink.writeAll(response.body().source());
            bufferedSink.close();
        }catch(Exception e){
            Log.e(TAG, "== got error in writeHttpResponseToFile");
            e.printStackTrace();
        }
        return fileName;

    }

    public String getMimeTypeBySuffix(String url){
        String result = "";
        if(url.endsWith("png") || url.endsWith("PNG")){
            result = "image/png";
        }else if (url.endsWith("jpg") || url.endsWith("JPG")
                || url.endsWith("jpeg") || url.endsWith("JPEG")){
            result = "image/jpg";
        }else if (url.endsWith("css") || url.endsWith("css.map")){
            result = "text/css";
        }else if (url.endsWith("js") ||url.endsWith(".js.map") ){
            result = "application/javascript";
        }else{
            result = "text/plain";
        }
        return result;
    }
}

然后在 webView 被调用之前, 使用:

         

        webView.setWebViewClient(new GenericWebViewClient(getApplicationContext().getCacheDir()));
        // 使用chrome client , 这样网页才能正常运行,弹出alert啥的。
        webView.setWebChromeClient(new WebChromeClient());
        webView.loadUrl("http://queentownh5.wenyc.cn");

订阅/RSS Feed

Subscribe

分类/category