天天看点

Java加载js

android 中可以通过webview来实现和js的交互,在程序中调用js代码,只需要将webview控件的支持js的属性设置为true

android(java)与javascript(html)交互有四种情况:

1) android(java)调用html中js代码

2) android(java)调用html中js代码(带参数)

3) html中js调用android(java)代码

4) html中js调用android(java)代码(带参数)

代码如下:

android端

mainactivity:

Java加载js

package com.home.jsandandroid;  

import android.app.activity;  

import android.os.bundle;  

import android.view.keyevent;  

import android.view.view;  

import android.webkit.webchromeclient;  

import android.webkit.websettings;  

import android.webkit.webview;  

import android.widget.toast;  

public class mainactivity extends activity {  

    private webview mwebview;  

    @override  

    protected void oncreate(bundle savedinstancestate) {  

        super.oncreate(savedinstancestate);  

        showwebview();  

    }  

    /** 

     * 显示webview并实现webview与js交互 

     */  

    private void showwebview() {  

        try {  

            mwebview = new webview(this);  

            setcontentview(mwebview);  

            mwebview.requestfocus();  

            mwebview.setwebchromeclient(new webchromeclient() {  

                @override  

                public void onprogresschanged(webview view, int progress) {  

                    mainactivity.this.settitle("loading...");  

                    mainactivity.this.setprogress(progress);  

                    if (progress >= 80) {  

                        mainactivity.this.settitle("jsandroid test");  

                    }  

                }  

            });  

            mwebview.setonkeylistener(new view.onkeylistener() { // webview can  

                                                                    // go back  

                public boolean onkey(view v, int keycode, keyevent event) {  

                    if (keycode == keyevent.keycode_back  

                            && mwebview.cangoback()) {  

                        mwebview.goback();  

                        return true;  

                    return false;  

            websettings websettings = mwebview.getsettings();  

            websettings.setjavascriptenabled(true);  

            websettings.setdefaulttextencodingname("utf-8");  

            mwebview.addjavascriptinterface(gethtmlobject(), "jsobj");  

            // 此html放在assets目录下  

            mwebview.loadurl("file:///android_asset/test.html");  

            // 如果html直接来源于网页上,可以使用下面形式  

            // mwebview.loadurl("http://192.168.1.121:8080/jsandroid/index.html");  

        } catch (exception e) {  

            e.printstacktrace();  

        }  

    private object gethtmlobject() {  

        object insertobj = new object() {  

            public string htmlcalljava() {  

                return "html call java";  

            }  

            public string htmlcalljava2(final string param) {  

                return "html call java : " + param;  

            public void javacallhtml() {  

                runonuithread(new runnable() {  

                    @override  

                    public void run() {  

                        mwebview.loadurl("javascript: showfromhtml()");  

                        toast.maketext(mainactivity.this, "clickbtn",  

                                toast.length_short).show();  

                });  

            public void javacallhtml2() {  

                        mwebview.loadurl("javascript: showfromhtml2('it-homer blog')");  

                        toast.maketext(mainactivity.this, "clickbtn2",  

        };  

        return insertobj;  

}  

js(html):

Java加载js

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">  

<!-- saved from url=(0032)http://localhost:8080/jsandroid/ -->  

<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="content-type" content="text/html; charset=utf-8">  

<meta http-equiv="expires" content="0">  

<meta http-equiv="pragma" content="no-cache">  

<meta http-equiv="cache-control" content="no-store,no-cache">   

<meta name="handheldfriendly" content="true">  

<meta name="viewport" content="width=100%; initial-scale=1.0; user-scalable=yes">  

<meta name="robots" content="all">  

<meta name="keywords" contect="doodle, mobile, doodlemobile, game, games">  

<meta name="description" content="make people's mobile life more connected through games.">  

<title>jsandroid_test</title>  

<script type="text/javascript" language="javascript">   

    function showhtmlcalljava(){  

        var str = window.jsobj.htmlcalljava();  

        alert(str);  

    function showhtmlcalljava2(){  

        var str = window.jsobj.htmlcalljava2("it-homer blog");  

    function showfromhtml(){  

        document.getelementbyid("id_input").value = "java call html";  

    function showfromhtml2( param ){  

        document.getelementbyid("id_input2").value = "java call html : " + param;   

</script>  

</head>  

<body>  

hello it-homer  

<br>  

<input type="button" value="htmlcalljava" onclick="showhtmlcalljava()" />  

<input type="button" value="htmlcalljava2" onclick="showhtmlcalljava2()" />  

<input id="id_input" style="width: 90%" type="text" value="null" />  

<input type="button" value="javacallhtml" onclick="window.jsobj.javacallhtml()" />  

<input id="id_input2" style="width: 90%" type="text" value="null" />  

<input type="button" value="javacallhtml2" onclick="window.jsobj.javacallhtml2()" />  

</body>  

</html>  

代码解析:

(1) 允许android执行js脚本设置

android(java)与js(html)交互的接口函数是: mwebview.addjavascriptinterface(gethtmlobject(), "jsobj");     // jsobj 为桥连对象

android容许执行js脚本需要设置: websettings.setjavascriptenabled(true);

(2) js(html)访问android(java)代码

js(html)访问android(java)端代码是通过jsobj对象实现的,调用jsobj对象中的函数,如: window.jsobj.htmlcalljava()

(3) android(java)访问js(html)代码

android(java)访问js(html)端代码是通过loadurl函数实现的,访问格式如:mwebview.loadurl("javascript: showfromhtml()");

说明:

1) android访问url网址,需在androidmanifest.xml文件,配置容许访问网络的权限:

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

2) android(java)调用js(html)时,使用的mwebview.loadurl("javascript: showfromhtml()");函数需在ui线程运行,因为mwebview为ui控件

Java加载js

public void javacallhtml(){  

    runonuithread(new runnable() {  

        @override  

        public void run() {  

            mwebview.loadurl("javascript: showfromhtml()");  

            toast.maketext(jsandroidactivity.this, "clickbtn", toast.length_short).show();  

    });