本文将引导您使用小程序的自定义双向通道功能。主要包含以下两部分内容:
打开 Android Studio,创建 MyJSApiPlugin
类让其继承 H5SimplePlugin
,实现自定义 H5 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;
}
}
在 MyApplication
中注册 MyJSApiPlugin
。
/*
* 第一个参数,自定义 API 类的全路径
* 第二个参数,BundleName,aar/inside 可以直接填 ""
* 第三个参数,作用于,可以直接填 "page"
* 第四个参数,作用的 API,将你自定义的 API 以 String[] 的形式传入
*/
MPNebula.registerH5Plugin(MyJSApiPlugin.class.getName(), "", "page", new String[]{MyJSApiPlugin.TINY_TO_NATIVE});
tiny-to-native.js
文件中添加如下代码实现小程序调用。
Page({
tinyToNative() {
my.call('tinyToNative', {
param1: 'p1aaa',
param2: 'p2bbb'
}, (result) => {
console.log(result);
my.showToast({
type: 'none',
content: result.message,
duration: 3000,
});
})
}
});
打开小程序开发者工具(IDE)中的 app.js
文件,添加小程序注册事件。
my.on('nativeToTiny', (res) => {
my.showToast({
type: 'none',
content: JSON.stringify(res),
duration: 3000,
success: () => {
},
fail: () => {
},
complete: () => {
}
});
})
在 Android Studio 中,修改 MainActivity
中 my_tv
的点击事件,向小程序端发送事件。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.my_tv).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MPNebula.startApp("2020092900000001");
new Thread(new Runnable() {
@Override
public void run() {
for (int index = 0;index < 5;index++){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
final int i = index;
runOnUiThread(new Runnable() {
@Override
public void run() {
H5Service h5Service = MPFramework.getExternalService(H5Service.class.getName());
final H5Page h5Page = h5Service.getTopH5Page();
if (null != h5Page) {
JSONObject jo = new JSONObject();
jo.put("key",i);
// native 向小程序发送事件的方法
// 第一个是事件名称,第二个是参数,第三个默认传 null
h5Page.getBridge().sendDataWarpToWeb("nativeToTiny", jo, null);
}
}
});
}
}
}).start();
}
});
}
}
在文档使用中是否遇到以下问题
更多建议
匿名提交