Android 與前端互動

瞌睡先生想睡覺發表於2018-02-27

public class MainActivity extends AppCompatActivity {

    private Button button;
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        webView = (WebView) findViewById(R.id.webView);

        initView();
    }

    private void initView() {

        webView.loadUrl("http://192.168.1.71:8080/test/");
        //Android 響應js呼叫
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new Test(), "hello");

        //Android 呼叫js
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webView.loadUrl("javascript:fun("+i+++")");
            }
        });
    }

    private int i = 0;
    public class Test {
        @JavascriptInterface
        public void showAndroid() {
            button.setText(String.valueOf(i++));
        }
    }

}
<html>
<head>
    <title>$Title$</title>

    <script>

        //響應Android的呼叫
        function fun(name) {
            var button = document.getElementById("button");
            button.innerText = name;
        }

    </script>
</head>
<body>

<button id="button" onclick="window.hello.showAndroid()">呼叫Android方法</button>

</body>
</html>

程式碼很簡單照著敲一遍就什麼都懂了

參照:https://www.cnblogs.com/cherrylv/p/6424199.html


2018/07/06
在新公司中又學到了他們進行互動的方法

repositories {
    // ...
    maven { url "https://jitpack.io" }
}

dependencies {
    compile 'com.github.lzyzsd:jsbridge:1.0.4'
}

參考:https://www.jianshu.com/p/b3d120753bbb
或者自行百度谷歌

相關文章