WebView使用
1.拿到WebView的标题
web.setWebChromeClient(new WebChromeClient(){
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
});
2.不要使用浏览器打开 使用Webview打开
web.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
}
);
3.下载文件的监听器 通过调用系统浏览器的进行下载 也可以通过线程自己下载
web.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri u=Uri.parse(url);
Intent i=new Intent(Intent.ACTION_VIEW,u);
startActivity(i);
}
});
3.1自定义线程类 用来下载文件
public class HttpThread extends Thread {
private String url;
public HttpThread(String url) {
this.url = url;
}
@Override
public void run() {
super.run();
try {
URL httpUrl = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) httpUrl.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
InputStream inputStream = urlConnection.getInputStream();
byte[] buf = new byte[6 * 1024];
File file;
int len;
FileOutputStream fos = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//如果sd卡挂载了
file = Environment.getExternalStorageDirectory();
File f = new File(file, "a.apk");
fos = new FileOutputStream(f);
}
Log.e("ggg","开始下载...");
while ((len = inputStream.read(buf)) != -1) {
if (fos != null) {
fos.write(buf, 0, len);
}
}
Log.e("ggg","下载完成");
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.2 开启线程进行下载操作
class s implements DownloadListener {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
if (url.endsWith(".apk")) {
new HttpThread(url).start();
}
}
}
}
4.webview网页加载错误时显示
web.setWebViewClient(new WebViewClient(){
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
view.loadUrl(“file:///android_asset/error.html”);
}
});
5.WebView与js调用发生混淆(正常情况下是没有问题的 但是当进行代码混淆的时候 就将js的函数打乱了 解决方法 在proguard-rules.pro文件中在代码混淆中添加
-keep public class 全类名{
public
}
)
6.在WebView的shouldOverrideUrlLoading方法进行协议拦截