主要内容:
- 关于通信的一些思考
- React Js 与 Native 之间的通信的三种方式
- React Js 与 Native 通信三种方式的比较
- React Js 与 Native 之间的通信的基本原理
一、关于通信的一些思考
1、进程间的通信:
在Android 系统中,应用是运行在由多个线程组成的进程中的,有的应用包含一个进程,有的可能会有两个进程,甚至多个进程。Android 系统中常见的进程间通信方式有 Binder、AIDL、Messenger;
2、线程间的通信
在Android 中,线程与线程的通信方式有,Intent、Handler;
3、传统的Js 与 Android 之间的通信
场景一般是Andoid WebView 与 页面中加载的Js 方法之间的通信,使用 addJavascriptInterface 来实现两者之间的通信。
比如要实现,在Js 页面中调用 Android 中的 Toast提示,可以这样做:
Java 端:
mWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
// 声明一个@JavascriptInterface,
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
在 Js 端调用如下:
<button onclick="showAndroidToast('addjavascriptinterface');">showAndroidToast