android混合开发Android

Android中webveiw与H5进行交互

2018-12-29  本文已影响0人  谁动了我的代码QAQ

最近北京好冷呀!冻到哭泣。
最近正在做Android原生与h5界面交互的工作。记录一下学习的收获。
首先Android原生与js互相调用是在webview中完成的,在webview中可以加载html网页,但是根据html的位置不同加载方式也不太相同。

webview加载网页

加载网络上的网页

webView.loadUrl("https://www.baidu.com/");

注意:在使用的时候一定要加上网络权限

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

效果如下:


示例图片

加载本地的资源文件中的网页,也就是asset目录下的本地资源

webView.loadUrl("file:///android_asset/test.html");
示例图片

这样就可以将网页加载出来。
在初始化webview的时候还要设置一些属性才可以使Android原生和Js相互调用

WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);

只有设置这条属相为true,Android原生和JS才可以相互调用。

JS调用Android原生方法

先介绍一下h5网页中js语句调用Android原声的方法,在进行开发之前Android开发人员一定要和h5开发人员约定好互相调用的方法的名字,以及别名是什么。
这里我在h5网页中写了两个调用的方法

 <input type="button" value="Js调用Java代码" onclick="window.android.jsCallAndroid()"/>
 <input type="button" value="Js调用Java代码并传参数" onclick="window.android.jsCallAndroidArgs('Js传过来的参数')"/>

这里我定义了两个button,并通过window.android.方法名,来调用Android中的方法,其中android就是我定义的别名。
我需要的Android代码中也要设置别名

webView.addJavascriptInterface(new JsInterface(),"android");

其中JsInterface()是在Android中定义的一个内部类,“android”是和h5约定的别名。

public class JsInterface {
    
    @JavascriptInterface
    public void jsCallAndroid() {
       textView.setText("没有参数的js方法");
    }
    @JavascriptInterface
    public void jsCallAndroidArgs(String args) {
        textView.setText(args);
    }
}

点击h5中的button就可以调用这些方法,其中 @JavascriptInterface必须在每个方法的上面加上,否则无法调用方法。
h5中通过window.android.jsCallAndroid(),来调用无参数的方法,通过window.android.jsCallAndroidArgs('Js传过来的参数'),调用有参数的方法。调用后改变textview中的值。
当点击了一个按钮时,TextView中的值改变:


示例图片

当点击了第二个按钮时,TextView的值改变:


示例图片
这样就完成了h5的方法调用Android原生方法。

Android原生调用H5方法

先看一下H5中的方法

<script type="text/javascript">
        function javacalljs(){
             document.getElementById("showmsg").innerHTML = "JAVA调用了JS的无参函数";
         }

        function javacalljswith(arg){
             document.getElementById("showmsg").innerHTML = (arg);
        }
</script>

方法的作用很明确,通过这个方法来改变id为“showmsg”的值。并且第一个方法没有参数,第二个方法有参数。
在Android原生中的调用:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //通过此方式来调用无参方法
            webView.loadUrl("javascript:javacalljs()");
        }
    });
button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //通过此方式来调用有参方法
            webView.loadUrl("javascript:javacalljswith('啦啦啦啦')");
        }
    });

代码就很简单了,直接调用就可以了。

webView.loadUrl("javascript:方法名(参数))");

当点击了“点击我一下”后,h5中的内容发生改变


示例图片

当点击了“点第二个”按钮的时候


示例图片
ok,这里在webview里Android和h5交互就完成了,贴一下完整代码
public class MainActivity extends AppCompatActivity {
     private WebView webView;
     private Button button,button1;
     private TextView textView;

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webView);
        button = findViewById(R.id.button);
        button1 = findViewById(R.id.button1);
        textView = findViewById(R.id.text);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/test.html");
        //webView.loadUrl("https://www.jianshu.com/u/2021d79d4a28");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
             public void onClick(View v) {
                webView.loadUrl("javascript:javacalljs()");
             }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               webView.loadUrl("javascript:javacalljswith('啦啦啦啦')");
            }
       });
        webView.addJavascriptInterface(new JsInterface(),"android");
    }


   public class JsInterface {

       @JavascriptInterface
       public void jsCallAndroid() {
          textView.setText("没有参数的js方法");
       }
       @JavascriptInterface
       public void jsCallAndroidArgs(String args) {
          textView.setText(args);
      }
  }
}

布局文件:

<LinearLayout 
   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"
   tools:context=".MainActivity"
   android:orientation="vertical">

   <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.5">
    </WebView>
    <TextView
         android:id="@+id/text"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:layout_weight="1"
         android:text="测试"/>
   <RelativeLayout
        android:id="@+id/relayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
       <Button
           android:id="@+id/button"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="点击我一下"/>

      <Button
           android:id="@+id/button1"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_alignParentTop="true"
           android:layout_toEndOf="@+id/button"
           android:layout_toRightOf="@+id/button"
           android:text="点第二个"/>

   </RelativeLayout>

</LinearLayout>

h5代码:

<html>
  <head>
     <meta http-equiv="Content-Type" content="text/html" charset="utf-8" />

       <script type="text/javascript">
          function javacalljs(){
              document.getElementById("showmsg").innerHTML = "JAVA调用了JS的无参函数";
           }

          function javacalljswith(arg){
              document.getElementById("showmsg").innerHTML = (arg);
           } 
      </script>

  </head>

  <body>
      <h3>Web模块</h3>

         <h3 id="showmsg">调用js显示结果</h3>

         <input type="button" value="Js调用Java代码" onclick="window.android.jsCallAndroid()"/>

         <input type="button" value="Js调用Java代码并传参数" onclick="window.android.jsCallAndroidArgs('Js传过来的参数')"/>
   </body>
</html>

打完收工!

上一篇 下一篇

猜你喜欢

热点阅读