在项目中需要用到Android给Uniapp发送消息,Uniapp端监听接收消息内容,系统自带的UniJSCallback用起来不灵活,修修改改了一个消息小组件,用起来很方便,遂记录!
这个组件可以用来给Uniapp回调第三方SDK的消息或者相机拍照的图片路径,等等吧。“消息”是一个载体。
1、Bean
public class MyEvent {
//数据
private Object data;
//事件来源 字符串
private String source;
//触发对象
private Object trigger;
public MyEvent(Object data) {
this.data = data;
}
public Object getTrigger() {
return trigger;
}
@Override
public String toString() {
return "MyEvent{" +
"data=" + data +
", source='" + source + '\'' +
", trigger=" + trigger +
'}';
}
public void setTrigger(Object trigger) {
this.trigger = trigger;
}
public MyEvent(Object data, String source) {
this.data = data;
this.source = source;
}
public MyEvent() {
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
}
2、事件管理类
/***
* 自定义事件管理类
*/
public class MyEventManager {
private static MyEventManager myEventManager;
private Map<String, Collection<MyListener>> listeners;
/**
* 不能外部 new
* 实例化
*/
private MyEventManager() {
this.listeners = new HashMap<String, Collection<MyListener>>();
}
/**
* 返回监听 总数
*
* @return
*/
public int getSize() {
int size = 0;
for (String str : listeners.keySet()) {
size = size + listeners.get(str).size();
}
return size;
}
public Map<String, Collection<MyListener>> getListeners() {
return listeners;
}
/**
* 单例模式
*
* @return
*/
public static MyEventManager getMyEventManager() {
if (myEventManager == null) {
synchronized (MyEventManager.class) {
if (myEventManager == null) {
myEventManager = new MyEventManager();
}
}
}
return myEventManager;
}
/***
* 添加事件
* @param listener 事件对象
* @param source 来源
*/
public MyListener addListener(MyListener listener, String source) {
if (listener != null && source != null) {
Collection<MyListener> myListeners = listeners.get(source);
if (myListeners == null) {
myListeners = new HashSet<MyListener>();
listeners.put(source, myListeners);
}
myListeners.add(listener);
}
return listener;
}
/***
* 添加事件
* @param source 来源
* @param listener 事件对象
*/
public MyListener addListener(String source, MyListener listener) {
return addListener(listener, source);
}
/**
* 移除监听
*
* @param listener
*/
public void removeListener(MyListener listener) {
if (listeners == null || listener == null) {
return;
}
//变量所有 找出相同的 删除
for (String str : listeners.keySet()) {
Collection collection = listeners.get(str);
Iterator<MyListener> iter = collection.iterator();
while (iter.hasNext()) {
MyListener next = (MyListener) iter.next();
if (next == listener) {
collection.remove(next);
return;
}
}
}
}
/***
* 发送数据
* @param data 数据
* @param source 来源
* @return
*/
public static MyEvent postMsg(Object data, String source) {
MyEventManager myEventManager = MyEventManager.getMyEventManager();
MyEvent myEvent = new MyEvent(data);
myEvent.setSource(source);
if (myEventManager.listeners == null)
return myEvent;
myEventManager.notifyListeners(myEvent, myEvent.getSource());
return myEvent;
}
/**
* 通知所有的myListener
* 相同的 (source) 来源才通知
*/
private void notifyListeners(MyEvent event, String source) {
//取出 key为source 的 监听器集合
Collection<MyListener> collection = listeners.get(source);
// Log.i(MyEventManager.class.getName(), source + "--->" + event.getData());
if (collection == null) {
return;
}
//遍历监听器集合
Iterator<MyListener> iter = collection.iterator();
while (iter.hasNext()) {
MyListener next = iter.next();
//通知回调
next.onChange(event);
}
//销毁事件对象
event = null;
}
}
3、回调
public interface MyListener extends EventListener {
void onChange(MyEvent myEvent);
}
以上3项就是完整的代码
4、代码功能实践
4.1Android给Uniapp发送消息,UniApp接收
Android发送
/**
postMsg()中,第一个参数是消息内容,第二个参数可以看作是标志位
*/
MyEventManager.postMsg("${msg?.obj.toString()}", "formAndroid")
Uniapp接收
注意!这里是uni端的代码!importClass()中填写的是MyEventManager在安卓项目中的全路径
const myEventManager = plus.android.importClass('com.xxxxx.msg.MyEventManager');
const eventManager = myEventManager.getMyEventManager();
initUniListener() {
const myListener = plus.android.implements('com.xxxxx.msg.MyListener', {
onChange: function(event) {
plus.android.importClass(event);
console.log("==日志==" + event.getData());
if (event.getSource() == 'formAndroid') {
// uni.showToast({
// title: JSON.stringify(event.getData()),
// icon:'none'
// });
}
}
})
// //添加监听器
eventManager.addListener("formAndroid", myListener);
}
4.2、uniApp发送给Android
uniapp发送
const myEventManager = plus.android.importClass('com.xxxxx.msg.MyEventManager');
const eventManager = myEventManager.getMyEventManager();
eventManager.postMsg("uniAPP-->Android", "fromUni-app")
Android接收
MyEventManager.getMyEventManager().addListener({ myEvent ->
if (myEvent.source.trim().equals("fromUni-app")) { //判断过滤
//从uniapp 或者原生传过来的数据
val data = myEvent.data
Toast.makeText(
mWXSDKInstance.context,
"==Uni传过来的数据====$data", Toast.LENGTH_SHORT
).show()
}
}, "fromUni-app")
5、注意事项
实践的过程中,发现UniJSCallback与我用到的消息组件不能并存!不然的话,消息组件就不起作用,问题原理我并未深究。。。。。。。例如下面两段代码:
两段代码中,一个有UniJSCallback参 一个无参,我实际用到的是第二段代码,跳转页面后做一些自动操作,然后用自定义的消息组件回调消息给Uni 端,如果加入UniJSCallback参,自定义的消息组件就无效了,很奇怪,我也没深究,直接就不传参了,,,,
也许大神可以解释。
@UniJSMethod(uiThread = true)
fun testPath(callback: UniJSCallback?) {
if (callback != null) {
val data = JSONObject()
data.put("testValue", "success")
callback.invoke(data)
}
}
@UniJSMethod(uiThread = true)
open fun selectCamera() {
//打开原生安卓页面
if (mWXSDKInstance != null && mWXSDKInstance.context is Activity) {
val intent = Intent(
mWXSDKInstance.context,
xxxxActivity::class.java
)
(mWXSDKInstance.context as Activity).startActivityForResult(intent, 5000)
}
}