Android与JavaScript交互初览

2017-03-23  本文已影响0人  jiaozi0203

Android与JavaScript交互初览

背景

年后换了工作,第一个接手的项目需要Android层与WebView的JavaScript交互

必备小知识
    var cars = new Array();
    var cars = ["Audi","BMW","Volvo"];
<script src="myscript.js"></script>
    file:///android_assert/*.html
    file:///sdcard/*.html
主要类
示例代码
<html lang="zh-cn">

<body>
    <a>js中调用本地方法</a>
    <script>
        function runFromJs() {
            document.getElementById("hello,web!").innerHTML="Hello,WebView, form Android!"
        }
        var aTag = document.getElementsByTagName('a')[0];
        aTag.addEventListener('click',function(){
            var demo = myObject.runFromAndroid("调用Android的本地方法funFromAndroid(String name)");
            aTag.innerHTML=demo;
            return false;
        },false);

    </script>
    <div id="hello,web!">Click!!!!</div>
</body>

</html>
package com.example.jiaozi.androidjsdemo;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import com.example.jiaozi.androidjsdemo.js.JSInteration;

public class MainActivity extends AppCompatActivity {

    private WebView mWebView;
    private Button mClickButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {

        mClickButton = (Button) findViewById(R.id.activity_main_btn);
        mClickButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.loadUrl("javascript:runFromJs()");
            }
        });

        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        mWebView.setWebViewClient(new WebViewClient() {

        });
        mWebView.addJavascriptInterface(new JSInteration(), "myObject");
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setBackgroundColor(Color.argb(0, 0, 0, 0));
        mWebView.loadUrl("file:///android_asset/jsTest.html");
    }

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <Button
        android:id="@+id/activity_main_btn"
        android:layout_width="368dp"
        android:layout_height="60dp"
        android:text="调用JavaScript!"
        />

    <WebView
        android:id="@+id/activity_main_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>

上一篇下一篇

猜你喜欢

热点阅读