Android中WebView的使用

本文介绍了Android中WebView的基本用法,包括设置网络权限、布局配置和错误页面处理。同时,探讨了WebView如何与JavaScript进行互调,通过创建接口类实现交互。此外,文章还提及了同步Cookie的问题,远程注入和自定义拦截的挑战,以及WebView开发中的常见问题和优化策略。
摘要由CSDN通过智能技术生成

WevView是一个可以显示网页的控件,它采用WebKit渲染引擎来显示网页。由于在实际开发中并未使用过WebView,所以对WebView并未有经验之谈,还有很多没有整理不打算写了,以后实际开发中在整理吧。本文参考慕课网、Android API。

1、基本用法

首先添加网络访问权限:

<uses-permissionandroid:name="android.permission.INTERNET"/>

布局文件,添加WebView控件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tev_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="30dp"
            android:text="title" />

        <ImageView
            android:id="@+id/img_refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:src="@drawable/icon_refresh_focus" />
    </LinearLayout>
	
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="10dp"
        style="?android:attr/progressBarStyleHorizontal"
        />

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

MainActivity.java

@SuppressLint("JavascriptInterface")
public class MainActivity extends Activity {

    TextView tev_title;
    ImageView img_refresh;
    ProgressBar progressBar;
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        webView = (WebView) findViewById(R.id.webView);
        // 默认使用系统浏览器加载网页
        webView.loadUrl("h://www.taobao.com/");
        //启用JavaScript
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 使用APP加载网页
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // 加载本地的错误网页
                // 可以改成本地xml
                view.loadUrl("file:///android_asset/error.html");
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                // webview添加title
                tev_title.setText(title);
                super.onReceivedTitle(view, title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                //设置进度条
                progressBar.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }

        });

        img_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 刷新webview
                webView.reload();
            }
        });

        // webview 下载文件
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String arg1, String arg2,
                                        String arg3, long arg4) {

                System.out.println("onDownloadStart:" + url);

                // 根据url下载文件,非系统浏览器
                url.endsWith(".apk");
                // 下载逻辑...

                // 使用系统浏览器下载文件
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    private void initView() {
        webView = (WebView) findViewById(R.id.webView);
        tev_title = (TextView) findViewById(R.id.tev_title);
        img_refresh = (ImageView) findViewById(R.id.img_refresh);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); //goBack()表示返回WebView的上一页面    
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}

file:///android_asset/error.html

404 ERROR

2、与JavaScript互相调用

与JavaScript互相调用,需要创建JavaScript代码和客户端代码之间的接口类进行交互操作。

/**
 * 创建您的JavaScript代码和客户端代码之间的接口类
 */
public class JavaScriptInterface {
	Context mContext;

	/** Instantiate the interface and set the context */
	public JavaScriptInterface(Context c) {
		mContext = c;
	}

	/** Show a toast from the web page */
	@JavascriptInterface
	public void show(String toast) {
		Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
	}
}

MainActivity.java

// webview与JavaScript的调用(代码混淆的时候 java类需要keep掉,即不能被混淆, 不然调用失败)
webView = (WebView) findViewById(R.id.webView);
btn_androidToJavaScript= (Button) findViewById(R.id.btn_toJs);
//启用JavaScript
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/index.html");
// 设置编码
webView.getSettings().setDefaultTextEncodingName("utf-8");
// 添加一个对象, 让JS可以访问该对象的方法, 该对象中也可以调用JS中的方法
webView.addJavascriptInterface(new JavaScriptInterface(this), "android");
btn_androidToJavaScript.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        //调用js的jsShow()2方法
        webView.loadUrl("javascript:jsShow2()");
        }
 });

file:///android_asset/index.html

<html>
<head>
    <title>My JSP 'index.jsp' starting page</title>
    <script>
    function jsShow(){
    //调用android的show方法
    android.show("JavaScript to Android!");
    }
	//将由android调用
    function jsShow2(){
    document.getElementById("id_a").innerHTML="Android to JavaScript!";
   }

    </script>
</head>

<body>
<!--调用android中的show()方法 -->
<a onclick="jsShow()">This is my JSP page! </a><br>
<a id="id_a"></a><br>
</body>
</html>

3、同步Cookie问题

4、远程注入问题和自定义拦截问题

5、WebView开发问题及优化汇总

转战:http://blog.csdn.net/smartbetter/article/details/50659089;

提高效率!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值