Android中WebView和JavaScript通信

         Android提供了webview和JavaScript之间通信的api,这样就能做到native程序和html程序之间的交互,看下面的例子(html中调用js,传递两个字符串给java程序):


java代码:

public class AndroidJsDemoActivity extends Activity {
	
	private WebView mWebView; 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = mWebView.getSettings(); 
        webSettings.setSavePassword(false); 
        webSettings.setSaveFormData(false); 
        webSettings.setJavaScriptEnabled(true); 
        webSettings.setSupportZoom(true);
        mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "androidjsdemo");
        mWebView.loadUrl("file:///android_asset/demo.html"); 
    }
    final class DemoJavaScriptInterface {
        DemoJavaScriptInterface() { 
        } 
        public void  test(String str1,String str2){ 
            Intent intent=new Intent(AndroidJsDemoActivity.this,Activity2.class);
            Bundle b=new Bundle();
            b.putString("str1", str1);
            b.putString("str2", str2);
            intent.putExtras(b);
            startActivity(intent);
        } 
    }
}
html代码:
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
<title>Insert title here</title> 
</head> 
    <body>this is html page<p>
        <input type="submit" value="buttons" 
        onclick="androidjsdemo.test('ddd','fff')"/> 
    </body> 
</html>

重点看代码中标红部分。
androidjsdemo与java程序中
addJavascriptInterface(new DemoJavaScriptInterface(), "androidjsdemo")后面的参数对应
test('ddd','fff')是使用的 
DemoJavaScriptInterface的方法


/**
* @author 张兴业
* 邮箱:xy-zhang#163.com
* android开发进阶群:278401545
*
*/

posted @ 2012-03-26 15:45  张兴业  阅读(492)  评论(0编辑  收藏  举报