WebView的使用及实战,技术实现

39 阅读6分钟

总结

三套“算法宝典”

28天读完349页,这份阿里面试通关手册,助我闯进字节跳动

算法刷题LeetCode中文版(为例)

人与人存在很大的不同,我们都拥有各自的目标,在一线城市漂泊的我偶尔也会羡慕在老家踏踏实实开开心心养老的人,但是我深刻知道自己想要的是一年比一年有进步。

最后,我想说的是,无论你现在什么年龄,位于什么城市,拥有什么背景或学历,跟你比较的人永远都是你自己,所以明年的你看看与今年的你是否有差距,不想做咸鱼的人,只能用尽全力去跳跃。祝愿,明年的你会更好!

由于篇幅有限,下篇的面试技术攻克篇只能够展示出部分的面试题,详细完整版以及答案解析,有需要的可以关注

开源分享:docs.qq.com/doc/DSmRnRG… if (newProgress != 100) {

mProgressBar.setProgress(newProgress);

} else {

mProgressBar.setVisibility(View.GONE);

}

}

@Override

public void onReceivedTitle(WebView view, String title) {

super.onReceivedTitle(view, title);

mTvTitle.setText(title);

}

});

}

想大多数APP的做法一样,如微信,按下返回键,只是想后退,并不是想销毁Activity,我们可以这样做,重写 Activity的 onKeyDown()方法 ,并监听按下的键,采取 相应的 操作。

public boolean onKeyDown(int keyCode, KeyEvent event) {

if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) {

mWebView.goBack();

return true;

}

return super.onKeyDown(keyCode, event);

}

既然有后退操作,当然也有前进操作

//是够能够前进

mWebView.canGoForward();

//前进

mWebView.goForward();

第四步

调用该方法开始加载网页

mWebView.loadUrl(mUrl);

到此,webView的基本用法讲解到此。


webView 配置缓存


配置 缓存模式

缓存模式主要有一下几种:

  • LOAD_CACHE_ELSE_NETWORK

Use cached resources when they are available, even if they have expired.(如果本地有缓存,优先使用 本地 缓存,即使已经过期了 )

  • LOAD_CACHE_ONLY

Don’t use the network, load from the cache.(只使用本地 缓存)

  • LOAD_DEFAULT

Default cache usage mode.(默认的缓存 模式)

  • LOAD_NORMAL

This constant was deprecated in API level 17. This value is obsolete, as from API level HONEYCOMB and onwards it has the same effect as LOAD_DEFAULT.

  • LOAD_NO_CACHE

Don’t use the cache, load from the network.(不使用 本地缓存 )

我们可以通过以下方法设置缓存模式

WebSettings settings = mWebView.getSettings();

settings.setCacheMode(WebSettings.LOAD_DEFAULT);


webView请求错误时候的处理


因为系统自带的 错误页面太丑了,所以我们经常会对其 进行处理,目前本人了解到的主要有两种方法

- 加载本地的控件,显示 错误信息

- 加载自己 定义的 html页面

加载本地的控件

@SuppressWarnings("deprecation")

@Override

public void onReceivedError(WebView view, int errorCode, String description, String

failingUrl) {

super.onReceivedError(view, errorCode, description, failingUrl);

if (errorCode == 404) {

//用javascript隐藏系统定义的404页面信息

//String data = "Page NO FOUND!";

// view.loadUrl("javascript:document.body.innerHTML="" + data + """);

mWebView.setVisibility(View.INVISIBLE);

mErrorView.setVisibility(View.VISIBLE);

}

}

加载 定义的 html页面

@SuppressWarnings("deprecation")

@Override

public void onReceivedError(WebView view, int errorCode, String description, String

failingUrl) {

super.onReceivedError(view, errorCode, description, failingUrl);

if (errorCode == 404) {

//用javascript隐藏系统定义的404页面信息

String data = "Page NO FOUND!";

view.loadUrl("javascript:document.body.innerHTML="" + data + """);

}

}

当然实际开发中为了给用户比较还要的体验,会做非常多的处理,包括有网络情况和没有网络情况的处理,对于没有网络情况的处理,这里我们跳转到打开WiFi界面,详情可以参照我的 上一篇博客android 监听网络状态的变化及实战,而对于有网络情况的处理,这里我们只处理404错误,其他错误请根据项目的需求自行处理。

@SuppressWarnings("deprecation")

@Override

public void onReceivedError(WebView view, int errorCode, String description, String

failingUrl) {

super.onReceivedError(view, errorCode, description, failingUrl);

// 没有网络连接

if (false == APP.getInstance().isConnected()) {

APP.getInstance().showWifiDlg(NewsDetailActivity.this);

} else {

if (errorCode == 404) {

//用javascript隐藏系统定义的404页面信息

String data = "Page NO FOUND!";

view.loadUrl("javascript:document.body.innerHTML="" + data + """);

mWebView.setVisibility(View.INVISIBLE);

} else {//其他状态码错误的处理,这里就不罗列出来了

}

}

}


webView cookie的同步与清除


关于这个问题,我们主要分为两步,

- 怎样获取cookie

- 怎样将cookie与webView进行 同步

对于怎样获取 cookie,主要有以下方法

下面只给出核心代码

第一,使用DefaultHttpClient

DefaultHttpClient client = new DefaultHttpClient();

CookieStore store = client.getCookieStore();

List list = store.getCookies();

第二,使用HttpURLConnection

URLConnection con= (HttpURLConnection) url.openConnection();

// 取得sessionid.

String cookieval = con.getHeaderField("set-cookie");

String sessionid;

if(cookieval != null) {

sessionid = cookieval.substring(0, cookieval.indexOf(";"));

}

发送设置cookie:

URL url = new URL(requrl);

HttpURLConnectioncon= (HttpURLConnection) url.openConnection();

if(sessionid != null) {

con.setRequestProperty("cookie", sessionid);

}

第三,使用Retrofit

Call call = tnGouAPi.getTest(test);

call.enqueue(new Callback() {

@Override

public void onResponse(Call call, Response response) {

ResponseBody body = response.body();

Headers headers = response.headers();

Set names = headers.names();

for(String key:names){

String value = headers.get(key);

}

try {

Logger.i("onResponse: body=" + body.string());

} catch (IOException e) {

e.printStackTrace();

}

}

@Override

public void onFailure(Call call, Throwable t) {

Logger.i("onResponse: t=" + t.getMessage());

}

});

cookie 同步

/**

  • cookie同步

*/

@SuppressWarnings("deprecation")

private void syncCookieToWebView(String url,List cookies)

{

CookieSyncManager.createInstance(this);

CookieManager cm = CookieManager.getInstance();

cm.setAcceptCookie(true);

if(cookies!=null)

{

for (String cookie : cookies)

{

cm.setCookie(url,cookie);//注意端口号和域名,这种方式可以同步所有cookie,包括sessionid

}

}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {

CookieManager.getInstance().flush();

} else {

CookieSyncManager.getInstance().sync();

}

}

清除cookie

@SuppressWarnings("deprecation")

public void clearCookies(Context context) {

CookieSyncManager.createInstance(context);

CookieManager cookieManager = CookieManager.getInstance();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

cookieManager.removeAllCookies(null);

} else {

cookieManager.removeAllCookie();

}

}

注意事项

  1. 同步cookie要在WebView加载url之前,否则WebView无法获得相应的cookie,也就无法通过验证。

  2. 每次登录成功后都需要调用”syncCookie”方法将cookie同步到WebView中,同时也达到了更新WebView的cookie。如果登录后没有及时将cookie同步到WebView可能导致WebView拿的是旧的session id和服务器进行通信。


webView 下载文件的两种方法


总共 有两种 方法,

- 第一种,自己实现实现逻辑 ,下载,保存到相应目录;

- 第二种,调用系统的下载方法

核心代码如下

主要是给webView设置DownloadListener监听器

mWebView.setDownloadListener(new DownloadListener() {

@Override

public void onDownloadStart(String url, String userAgent, String contentDisposition,

String mimetype, long contentLength) {

//第一种下载方式是 自定义的http工具类

// new HttpDownloadThread(url,contentDisposition,mimetype,contentLength).start();

//第二种下载方式是调用系统的webView,具有默认的进度条

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setData(Uri.parse(url));

startActivity(intent);

}

});

HttpDownloadThread

public class HttpDownloadThread extends Thread {

private String mUrl;

private String mContentDisposition;

private String mMimetype;

private long mContentLength;

public HttpDownloadThread(String url, String contentDisposition, String mimetype, long contentLength) {

this.mUrl = url;

this.mContentDisposition=contentDisposition;

this.mContentDisposition=mimetype;

this.mContentDisposition=contentDisposition;

}

@Override

public void run() {

URL url;

try {

url = new URL(mUrl);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoInput(true);

conn.setDoOutput(true);

InputStream in = conn.getInputStream();

File downloadFile;

File sdFile;

FileOutputStream out = null;

if(Environment.getExternalStorageState().equals(Environment.MEDIA_UNMOUNTED)){

downloadFile = Environment.getExternalStorageDirectory();

sdFile = new File(downloadFile, "test.file");

out = new FileOutputStream(sdFile);

}

//buffer 4k

byte[] buffer = new byte[1024 * 4];

int len = 0;

while((len = in.read(buffer)) != -1){

if(out != null)

out.write(buffer, 0, len);

}

//close resource

if(out != null)

out.close();

if(in != null){

in.close();

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

学习笔记

主要内容包括html,css,html5,css3,JavaScript,正则表达式,函数,BOM,DOM,jQuery,AJAX,vue等等

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

HTML/CSS

**HTML:**HTML基本结构,标签属性,事件属性,文本标签,多媒体标签,列表 / 表格 / 表单标签,其他语义化标签,网页结构,模块划分

**CSS:**CSS代码语法,CSS 放置位置,CSS的继承,选择器的种类/优先级,背景样式,字体样式,文本属性,基本样式,样式重置,盒模型样式,浮动float,定位position,浏览器默认样式

HTML5 /CSS3

**HTML5:**HTML5 的优势,HTML5 废弃元素,HTML5 新增元素,HTML5 表单相关元素和属性

**CSS3:**CSS3 新增选择器,CSS3 新增属性,新增变形动画属性,3D变形属性,CSS3 的过渡属性,CSS3 的动画属性,CSS3 新增多列属性,CSS3新增单位,弹性盒模型

JavaScript

**JavaScript:**JavaScript基础,JavaScript数据类型,算术运算,强制转换,赋值运算,关系运算,逻辑运算,三元运算,分支循环,switch,while,do-while,for,break,continue,数组,数组方法,二维数组,字符串