package com.secondworld.sdk;
|
|
import com.secondworld.sdk.command.CmdInit;
|
import com.secondworld.sdk.command.ICommand;
|
import com.secondworld.sdk.utils.LogUtil;
|
import com.secondworld.sdk.utils.StaticDefine;
|
import com.unity3d.player.UnityPlayer;
|
|
import org.json.JSONObject;
|
|
import java.io.IOException;
|
import java.util.ArrayList;
|
import java.util.Enumeration;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
|
import dalvik.system.DexFile;
|
|
|
public class UnityMsgHandler {
|
|
private static final HashMap<Integer, ICommand> allCommand = new HashMap<>();
|
|
/**
|
* 初始化所有命令
|
*/
|
public static void initCommandMap() {
|
try {
|
allCommand.clear();
|
new CmdInit();
|
List<String> classesName = getClassName("com.secondworld.sdk.command");
|
for (String name : classesName) {
|
Class<?> aClass = Class.forName(name);
|
LogUtil.debug("initCommandMap", name);
|
if (!aClass.isInterface() && ICommand.class.isAssignableFrom(aClass))//此处必须判断是否为ICommand子类,因为匿名类也会生成至此包
|
addCommand((ICommand) aClass.newInstance());
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
LogUtil.e("initCommandMap", e);
|
}
|
}
|
|
public static void addCommand(ICommand command) {
|
allCommand.put(command.getCode(), command);
|
}
|
|
/**
|
* 处理unity 发来的消息
|
*
|
* @param json
|
*/
|
public static void onUnityMessage(String json) {
|
try {
|
LogUtil.debug("onUnityMessage", json);
|
JSONObject _json = new JSONObject(json);
|
int code = _json.getInt("code");
|
ICommand command = allCommand.get(code);
|
if (command == null)
|
LogUtil.e("onUnityMessage", "未知命令" + code);
|
else
|
command.process(_json);
|
} catch (Exception e) {
|
LogUtil.e("onUnityMessage", e);
|
}
|
}
|
|
/**
|
* 通过反射读取指定包名下的所有类名
|
*
|
* @param
|
* @return
|
*/
|
public static List<String> getClassName(String packageName) throws IOException {
|
List<String> classNameList = new ArrayList<String>();
|
DexFile df = new DexFile(GameAppProxy.app.getPackageCodePath());//通过DexFile查找当前的APK中可执行文件
|
Enumeration<String> enumeration = df.entries();//获取df中的元素 这里包含了所有可执行的类名 该类名包含了包名+类名的方式
|
while (enumeration.hasMoreElements()) {//遍历
|
String className = (String) enumeration.nextElement();
|
if (className.contains(packageName)) {//在当前所有可执行的类里面查找包含有该包名的所有类
|
classNameList.add(className);
|
}
|
}
|
return classNameList;
|
}
|
|
public static void sendMessageToUnity(int code) {
|
UnityMsgHandler.sendMessageToUnity(code,null);
|
}
|
|
/**
|
* 发送消息到unity
|
*
|
* @param args
|
*/
|
public static void sendMessageToUnity(int code, Map<String, Object> args) {
|
if (args == null)
|
args = new HashMap<>();
|
args.put("code", code);
|
JSONObject jsonObject = new JSONObject(args);
|
if (GameAppProxy.isDemo()) {
|
LogUtil.debug("发送消息到unity", jsonObject.toString());
|
return;
|
}
|
UnityPlayer.UnitySendMessage(StaticDefine.UnityGameObjectName,
|
StaticDefine.UnityHandleFuncName,
|
jsonObject.toString());
|
}
|
|
}
|