android 调用js中的方法
16lz
2021-12-04
Android中可以使用WebView加载网页,同时Android端的java代码可以与网页上的javascript代码之间相互调用。
一 Android部分:
布局代码:
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableInTouchMode="true" android:orientation="vertical" android:padding="8dp" tools:context=".MainActivity"> android:layout_width="match_parent" android:layout_height="wrap_content"> android:id="@+id/input_et" android:layout_width="0dp" android:layout_height="wrap_content" android:singleLine="true" android:layout_weight="1" android:hint="请输入信息" /> android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" />
Activity代码: public class MainActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = (WebView) findViewById(R.id.webView); webView.setVerticalScrollbarOverlay(true); //设置WebView支持JavaScript webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("file:///android_asset/webview.html"); //在js中调用本地java方法 webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");// //添加客户端支持 webView.setWebChromeClient(new WebChromeClient()); } private class JsInterface { private Context mContext; public JsInterface(Context context) { this.mContext = context; } //在js中调用window.AndroidWebView.showInfoFromJs(name),便会触发此方法。 @JavascriptInterface public void showInfoFromJs(String name) { Toast.makeText(mContext, name, Toast.LENGTH_SHORT).show(); } } //在java中调用js代码 public void sendInfoToJs(View view) { String msg = ((EditText) findViewById(R.id.input_et)).getText().toString(); //调用js中的函数:showInfoFromJava(msg) webView.loadUrl("javascript:showInfoFromJava('" + msg + "')");// webView.loadUrl("javascript:showInfoFromJava()"); }}二 网页代码
html>lang="en"> charset="UTF-8"> Android WebView 与 Javascript 交互type="button" value="分享" οnclick="f1()">type="text" id="show"/>
注意: android 调用js代码可能会报错如下: W/WebView(2088): java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread.
解决办法:
webView.post(new Runnable() { @Override public void run() {
webView.loadUrl("javascript:showInfoFromJava('" + msg + "')");}}) ;
更多相关文章
- Android截取开机关机事件
- Android(安卓)Compatibility zoom dialog 关闭
- Dealing with bitmap object in android NDK
- android > 调用拨打电话 并子线程监控然后返回跳转
- android调用系统发短信界面功能
- android 触发器
- Android(安卓)获取版本号
- Android(安卓)源代码结构
- Android(安卓)Wifi Hotspot Manager Class