android javascript 调用activity
WebView 里有一个 addJavascriptInterface (Object obj, String interfaceName)方法,object为一个实例对象,你想用javascript调用的函数写在这代码如下:
package com.webview; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Toast; public class MainActivity extends Activity { private static final String LOG_TAG = "WebViewDemo"; private WebView mWebView; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); 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(false); mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo"); mWebView.loadUrl("http://192.168.1.201:8080/java.html"); } final class DemoJavaScriptInterface { DemoJavaScriptInterface() { } /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { // mWebView.loadUrl("javascript:wave()"); Toast.makeText(getBaseContext(), "123", Toast.LENGTH_SHORT).show(); } }); } } /** * Provides a hook for calling "alert" from javascript. Useful for * debugging your javascript. */ final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(LOG_TAG, message); result.confirm(); return true; } } }
在html里调用写法如下:
<a onClick="window.demo.clickOnAndroid()">click me</a>
相关推荐
dangai00 2020-07-18
xhpscdx 2020-05-31
chenxiangpeng 2020-04-30
ncuboy0wsq 2020-03-27
学习web前端 2020-03-23
APCDE 2020-03-04
歆萌 2020-03-03
csdnuuu 2020-01-04
水龙吟的备忘录 2019-11-18
icewizardry 2014-04-10
元元 2019-11-17
androidstudyroom 2019-11-08
czpaex 2011-09-11
OldSoldier 2011-08-18
wangdaiying 2011-05-26
qixiang0 2019-08-24