Android 小程序自定义双向通道
若已有小程序 API 或事件不满足开发需求,您可以自行扩展。
小程序调用原生自定义 API
客户端自定义 API 并注册。
自定义 API:
public class MyJSApiPlugin extends H5SimplePlugin {
/**
* 自定义 API
*/
public static final String TINY_TO_NATIVE = "tinyToNative";
@Override
public void onPrepare(H5EventFilter filter) {
super.onPrepare(filter);
// onPrepare 中需要 add 进来
filter.addAction(TINY_TO_NATIVE);
}
@Override
public boolean handleEvent(H5Event event, H5BridgeContext context) {
String action = event.getAction();
if (TINY_TO_NATIVE.equalsIgnoreCase(action)) {
JSONObject params = event.getParam();
String param1 = params.getString("param1");
String param2 = params.getString("param2");
JSONObject result = new JSONObject();
result.put("success", true);
result.put("message", "客户端接收到参数:" + param1 + ", " + param2 + "\n返回 Demo 当前包名:" + context.getActivity().getPackageName());
context.sendBridgeResult(result);
return true;
}
return false;
}
}
注册 API:启动小程序前全局注册一次即可。
/*
* 第一个参数,自定义 API 类的全路径
* 第二个参数,BundleName,aar/inside 可以直接填 ""
* 第三个参数,作用于页面级,可以直接填 "page"
* 第四个参数,作用的 API,将你自定义的 API 以 String[] 的形式传入
*/
MPNebula.registerH5Plugin(MyJSApiPlugin.class.getName(), "", "page", new String[]{MyJSApiPlugin.TINY_TO_NATIVE});
小程序调用。
my.call('tinyToNative', {
param1: 'p1aaa',
param2: 'p2bbb'
}, (result) => {
console.log(result);
my.showToast({
type: 'none',
content: result.message,
duration: 3000,
});
})
原生向小程序发送自定义事件
小程序注册事件。
my.on('nativeToTiny', (res) => {
my.showToast({
type: 'none',
content: JSON.stringify(res),
duration: 3000,
success: () => {
},
fail: () => {
},
complete: () => {
}
});
})
客户端发送事件
H5Service h5Service = MPFramework.getExternalService(H5Service.class.getName());
final H5Page h5Page = h5Service.getTopH5Page();
if (null != h5Page) {
JSONObject jo = new JSONObject();
jo.put("key", value);
// native 向小程序发送事件的方法
// 第一个是事件名称,第二个是参数,第三个默认传 null
h5Page.getBridge().sendDataWarpToWeb("nativeToTiny", jo, null);
}
取消注册自定义事件
如不再需要自定义事件,请参见 取消注册自定义事件。