当前位置: 移动技术网 > IT编程>移动开发>Android > Android与js互相调用

Android与js互相调用

2018年09月07日  | 移动技术网IT编程  | 我要评论

南阳小姐,福利部落,美神探爱琳

有话要说:

本篇主要总结了简单的android与js互相调用的方法。

在开发过程中遇到了需要在安卓中调用js方法的需求,于是将具体的实现过程总结成这篇博客。

效果:

其中“调用安卓方法”按钮是html中的按钮;“调用js方法”按钮是app中的按钮。

本地html:

首先,在app根目录新建一个assets文件夹,并在文件夹内新建一个本地html文件,如下图

接着编写一个简单的html文件:

 1 <html lang="zh-cn">
 2 <p id='p'>hello world</p>
 3 
 4 <script>
 5         function test(){
 6             document.getelementbyid("p").innerhtml += " 你好!"
 7         }
 8 </script>
 9 
10 <button onclick="justtest.hello('js调用安卓方法!')">调用安卓方法</button>
11 
12 </html>

 

android布局文件:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:orientation="vertical"
 7     tools:context=".mainactivity">
 8 
 9     <webview
10         android:id="@+id/webview"
11         android:layout_width="wrap_content"
12         android:layout_height="wrap_content" />
13 
14     <button
15         android:id="@+id/btn"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:text="调用js方法" />
19 
20 </linearlayout>

安卓调用js方法:

可以看到,在本地html中已经有了一个test函数,下面来在安卓中调用这个test函数。

加载本地html文件:

1 webview = findviewbyid(r.id.webview);
2 webview.getsettings().setjavascriptenabled(true);
3 webview.loadurl("file:///android_asset/show.html");

 

定义按钮的点击事件:

1 button btn = findviewbyid(r.id.btn);
2 
3 btn.setonclicklistener(new view.onclicklistener() {
4     @override
5     public void onclick(view v) {
6         testjs();
7     }
8 });

其中testjs代码为:

1 @suppresslint("setjavascriptenabled")
2 public void testjs() {
3     webview.loadurl("javascript:test()");
4 }

据此,就实现了安卓调用js方法。

js调用安卓方法:

首先,需要在activity中定义被调用的方法:

1 @javascriptinterface
2 public void hello(string msg) {
3     toast.maketext(this, msg, toast.length_short).show();
4 }

并且需要给webview绑定上java对象:

1 webview.addjavascriptinterface(this, "justtest");

最后,在js中调用该方法:

1 <button onclick="justtest.hello('js调用安卓方法!')">调用安卓方法</button>

这样就实现了在js中调用安卓方法。

总结:

由于工作繁忙,好久没写博客了。

以后会抽出时间多多总结自己在工作中所学习的内容的。

这篇博客写了一个很简单的一个demo,但是安卓和js互相调用在实际开发中很有用,特地做一个总结。

 

大家如果有什么疑问或者建议可以通过评论或者的方式联系我,欢迎大家的评论~

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网