Android WebView填坑记录

来源:互联网 发布:大数据信息化时代 编辑:程序博客网 时间:2024/06/01 22:04

http://blog.csdn.net/xueshanhaizi/article/details/51524805

http://blog.csdn.net/xueshanhaizi/article/details/51524805

http://blog.csdn.net/xueshanhaizi/article/details/51524805

http://blog.csdn.net/xueshanhaizi/article/details/51524805




 

Android WebView填坑记录

标签: androidwebview
 6574人阅读 评论(3) 收藏 举报
 分类:

目录(?)[+]

前言

       在应用程序开发过程中,经常会采用webview来展现某些界面,这样就可以不受发布版本控制,实时更新,遇到问题可以快速修复。

       但是在Android开发中,由于android版本分化严重,每一个版本针对webview都有部分更改,因此在开发过程中会遇到各种各样的坑,因此在此总结一下在开发过程中遇到的一些坑!

样例

       这里不是讲解怎么进行webview开发,而是只罗列其中遇到的一些坑!为了展示这些问题,我们还是写一个样例来进行展开。

       样例代码:

/** * WebView demo */public class WebViewActivity extends AppCompatActivity {    public static void start(Context context) {        Intent intent = new Intent();        intent.setClass(context, WebViewActivity.class);        context.startActivity(intent);    }    private static final String TAG = "WebViewActivity";    public static final String URL = "http://www.163.com";    private static final int REQUEST_CODE_GET_LOCAL_FILE = 0;    private static final int REQUEST_CODE_GET_LOCAL_FILE_NEW = 1;    private WebView webView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_web_view);        findViews();        initWebView();    }    /**     * 查找界面view     */    private void findViews() {        webView = (WebView) findViewById(R.id.web_view);    }    /**     * 初始化webview参数     */    private void initWebView() {        initWebSetting();        setAcceptThirdPartyCookies();        initWebClient();        loadUrl();    }    /**     * 加载地址     */    private void loadUrl() {        webView.loadUrl(URL);    }    /**     * 设置WebSetting     */    private void initWebSetting() {        WebSettings webSettings = webView.getSettings();        webSettings.setJavaScriptEnabled(true);        webSettings.setDomStorageEnabled(true);        webSettings.setLoadWithOverviewMode(true);        webSettings.setUseWideViewPort(true);        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);        webSettings.setUserAgentString(webSettings.getUserAgentString() + " VersionCode/" + InstallUtil                .getVersionCode(this));        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);        webSettings.setAllowFileAccess(true);        webSettings.setAppCacheEnabled(true);        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);        webSettings.setSupportZoom(true);        webSettings.setGeolocationEnabled(true);        webSettings.setDatabaseEnabled(true);        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);        }    }    /**     * 设置跨域cookie读取     */    public final void setAcceptThirdPartyCookies() {        //target 23 default false, so manual set true        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);        }    }    /**     * 设置client     */    private void initWebClient() {        webView.setWebChromeClient(new WebChromeClient() {            @Override            public void onProgressChanged(WebView view, int newProgress) {                super.onProgressChanged(view, newProgress);                Log.e(TAG, "onProgressChanged newProgress=" + newProgress);            }            @TargetApi(Build.VERSION_CODES.LOLLIPOP)            @Override            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,                                              FileChooserParams fileChooserParams) {                uploadFileNew = filePathCallback;                Intent intent = fileChooserParams.createIntent();                try {                    startActivityForResult(intent, REQUEST_CODE_GET_LOCAL_FILE_NEW);                } catch (Exception e) {                    ToastUtil.showLong(getString(R.string.choose_fail));                    return false;                }                return true;            }            //            // FILE UPLOAD <3.0            //            public void openFileChooser(ValueCallback<Uri> uploadFile) {                chooseFile(uploadFile, null, null);            }            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType) {                chooseFile(uploadFile, acceptType, null);            }            /**             * 4.x             * @param uploadFile             * @param acceptType             * @param capture             */            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {                chooseFile(uploadFile, acceptType, capture);            }        });        webView.setWebViewClient(new WebViewClient() {            @Override            public void onPageStarted(WebView view, String url, Bitmap favicon) {                super.onPageStarted(view, url, favicon);                Log.e(TAG, "onPageStarted");            }            @Override            public void onPageFinished(WebView view, String url) {                super.onPageFinished(view, url);                Log.e(TAG, "onPageFinished");            }            @Override            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {                super.onReceivedError(view, request, error);                Log.e(TAG, "onReceivedError");            }            @Override            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {                super.onReceivedSslError(view, handler, error);                Log.e(TAG, "onReceivedSslError");            }            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {                Log.e(TAG, "shouldOverrideUrlLoading url=" + url);                return super.shouldOverrideUrlLoading(view, url);            }        });    }    private ValueCallback<Uri[]> uploadFileNew;    private ValueCallback<Uri> uploadFile;    /**     * 文件选择     *     * @param uploadFile     * @param acceptType     * @param capture     */    private void chooseFile(ValueCallback<Uri> uploadFile, String acceptType, String capture) {        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);        if (TextUtils.isEmpty(acceptType)) {            acceptType = "*/*";        }        intent.setType(acceptType);        this.uploadFile = uploadFile;        try {            startActivityForResult(Intent.createChooser(intent, capture), REQUEST_CODE_GET_LOCAL_FILE);        } catch (Throwable tr) {            tr.printStackTrace();        }    }    @TargetApi(Build.VERSION_CODES.LOLLIPOP)    @Override    public void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        switch (requestCode) {            case REQUEST_CODE_GET_LOCAL_FILE:                if (uploadFile != null) {                    uploadFile.onReceiveValue((resultCode == Activity.RESULT_OK && data != null) ? data.getData() :                             null);                    uploadFile = null;                }                break;            case REQUEST_CODE_GET_LOCAL_FILE_NEW:                if (uploadFileNew != null) {                    uploadFileNew.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));                    uploadFileNew = null;                }                break;        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213

       布局代码

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.sunny.demo.webview.WebViewActivity">    <WebView        android:id="@+id/web_view"        android:layout_width="match_parent"        android:layout_height="match_parent">    </WebView></RelativeLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

填坑

1,回调不成对

       在WebView加载地址时,在加载过程中回调次数不一定相同,比如这里我们我们加载http://www.163.com。

E/WebViewActivity: onProgressChanged newProgress=10E/WebViewActivity: onPageStartedE/WebViewActivity: shouldOverrideUrlLoading url=http://3g.163.com/E/WebViewActivity: onPageStartedE/WebViewActivity: onPageStartedE/WebViewActivity: shouldOverrideUrlLoading url=http://3g.163.com/touch/E/WebViewActivity: onProgressChanged newProgress=50E/WebViewActivity: onPageFinishedE/WebViewActivity: onProgressChanged newProgress=52E/WebViewActivity: onProgressChanged newProgress=90E/WebViewActivity: onProgressChanged newProgress=95E/WebViewActivity: onProgressChanged newProgress=100E/WebViewActivity: onPageFinished
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

       从上面的日志中可以看到onPageStarted与onPageFinished次数不一致,因此如果你在start中进行进度条加载处理,finish中结束,会导致进度条一直不消失。因此可以在onProgressChanged进行处理。当newProgress为100时表示页面加载完成。

2,文件选择回调函数更改

       如果你是web页面开发人员,如果要选取本地文件,可以采用input标签,如下一个简单的html页面:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title></head><body>    <input type="file" accept="image/*;" capture="camera" >    <a href="test1.html">url替换为test1页面</a>    <script>    var a = function() {        //alert(1);    };    document.addEventListener('JSBridgeReady',a);    </script></body></html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

附录 
如果你不是专业的web开发人员,但是又想进行web页面调试,可以自己搭建一个web服务,如果你采用的是MAC可以采用如下方案进行web服务搭建

1.用node装一个http-server

2.brew install node

3.npm install -g http-server 安装

4.在一个目录下 http-server启动就是一个简单http服务里 port 8080

        上面的代码加载后效果如下: 
这里写图片描述

       很简单吧!是不是想说so easy!!!那我们就点击一下选择文件吧!

咦没效果 
换手机,好,有效果 
再换,咦,又没有效果

       是不是感觉很抓狂?这是由于Android的不同版本,WebView的回调函数都不一致。怎么解决这个问题?可以复写不同的回调函数,这里主要有以下四个回调函数,分别处理不同的版本:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)@Overridepublic boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,                                 FileChooserParams fileChooserParams) {    Intent intent = fileChooserParams.createIntent();    try {        startActivityForResult(intent, REQUEST_CODE_GET_LOCAL_FILE_NEW);    } catch (Exception e) {        ToastUtil.showLong(getString(R.string.choose_fail));        return false;    }    return true;}//// FILE UPLOAD <3.0//public void openFileChooser(ValueCallback<Uri> uploadFile) {    chooseFile(uploadFile, null, null);}public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType) {    chooseFile(uploadFile, acceptType, null);}/** * 4.x * @param uploadFile * @param acceptType * @param capture */public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {    chooseFile(uploadFile, acceptType, capture);}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

       复写了上述四个函数,同时记得onActivityResult进行返回结果处理。就算是这样,我也不敢保证所有的手机都能正确的进行处理。 
       刚才在html中是否看到了一个一段document.addEventListener(‘JSBridgeReady’,a)这样的代码。这里是想说给出另外一种解决方案,可以采用JSBridge方式进行web页面与native页面交互,这样就可以屏蔽版本中间的差异。

3,跨域cookie读取

       什么是跨域,简单的说就是不同的域名,我们都知道在pc上我们用浏览器访问网址,不同的网址都会在本地存储一些cookie信息,这样就可以实现比如自动登录等功能,在pc上不同域名是不能相互读取其他域下的cookie信息的(非web专业开发人员,如果理解有误,欢迎指出)。

       但是在Android上在api 23之前,是可以跨域读取cookie的,比如A域写入一个userId的cookie,B域可以读取该值。但是在23时,系统将该值设置成了false,不再让跨域读取了。如果你的应用有跨域读取需求,怎么办?可以采用如下方式进行开启:

    /**     * 设置跨域cookie读取     */    public final void setAcceptThirdPartyCookies() {        //target 23 default false, so manual set true        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);        }    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

       这里我们来看看setAcceptThirdPartyCookies的注释:

Sets whether the {@link WebView} should allow third party cookies to be set. 
Allowing third party cookies is a per WebView policy and can be set 
differently on different WebView instances. 


Apps that target {@link android.os.Build.VERSION_CODES#KITKAT} or below 
default to allowing third party cookies. Apps targeting 
{@link android.os.Build.VERSION_CODES#LOLLIPOP} or later default to disallowing 
third party cookies.

4,http/https混合加载

       在现阶段,很多网站都改成了https进行访问,https可以提升访问网站的安全性,防止信息被窃取,如果所有的网页都是https且网页内的链接也是都是https,那就没有混合加载的问题了。但是很多资源现阶段还没有改变成https访问,往往页面都嵌入了http的链接。这种混合网页如果不进行处理,直接加载是会出现错误的。怎么解决这个问题?

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {  webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);}
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

       这也是一个分版本的函数,在api 23之前,默认是可以混合加载的,但是在23时,默认值改成了MIXED_CONTENT_NEVER_ALLOW,因此如果你有混合加载的需求,设置setMixedContentMode为MIXED_CONTENT_ALWAYS_ALLOW。

5,花屏

       WebView如果开启了硬件加速,多次打开,会导致界面花屏,或者界面绘制有残留。这个在5.0刚出来的时候发生过多次,但是当时忘记截图了。当时也没有打算要把这些给记录下来。这里我已经复现不了了。如果你遇到了。关闭硬件加速就好了。

6,资源释放

       这里我们先截取几张图来看看加载前与加载后webview内存的占用: 
       加载之前: 
这里写图片描述
       加载之后: 
这里写图片描述
       退出页面: 
这里写图片描述

       可以看到内存蹭蹭蹭的就上去了。就算退出去了也没有减少多少,因此这里必须手动进行资源释放,可以调用如下代码:

@Overrideprotected void onDestroy() {    super.onDestroy();    if (webView != null) {        root.removeView(webView);        webView.removeAllViews();        webView.destroy();    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

       也可以采用在界面中动态创建webview,之后add到页面中,甚至更有人会为该页面单独设置一个进程,之后退出后会调用exit函数进行资源释放。这里可以根据需求来进行设置。

总结

       WebView有这样或者那样的坑。这里只是大致罗列自己遇到的一些,在知乎上也看到一个专门讲WebView坑的查看链接。大家可以去看看,有什么新的发现也可以进行探讨。

2