}
@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();
}
}
注意事项
-
同步cookie要在WebView加载url之前,否则WebView无法获得相应的cookie,也就无法通过验证。
-
每次登录成功后都需要调用”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();
}
}
}
webView的 一些扩展使用
最后
面试题千万不要死记,一定要自己理解,用自己的方式表达出来,在这里预祝各位成功拿下自己心仪的offer。