webview使用

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方法进行协议拦截

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值