lwb
2020-11-03 4bd30dd01b09d642eaddeade6e13aa36d9d353e4
SdkProject/library/src/main/java/com/secondworld/universalsdk/H2EngineSDK.java
@@ -1,4 +1,86 @@
package com.secondworld.universalsdk;
import android.util.Log;
import com.secondworld.universalsdk.command.ICommand;
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 dalvik.system.DexFile;
public class H2EngineSDK {
    private static HashMap<Integer, ICommand> allCommand = new HashMap<Integer, ICommand>();
    /**
     * 初始化所有命令
     */
    public static void initCommandMap() {
        allCommand.clear();
        List<String> classesName = getClassName("com.secondworld.universalsdk.command");
        try {
            for (String name : classesName) {
                Class<?> aClass = Class.forName(name);
                if (!aClass.isInterface())
                    addCommand((ICommand) aClass.newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void addCommand(ICommand command) {
        allCommand.put(command.getCode(), command);
    }
    /**
     * unity 发来的消息
     *
     * @param json
     */
    public static void HandleUnityMessage(String json) {
        try {
            LogUtil.debug("HandleUnityMessage", json);
            JSONObject _json = new JSONObject(json);
            int code = _json.getInt("code");
            ICommand command = allCommand.get(code);
            if (command == null) {
                return;
            }
            command.process(json);
        } catch (Exception ignored) {
        }
    }
    /**
     * 通过反射读取指定包名下的所有类名
     *
     * @param packageName
     * @return
     */
    public static List<String> getClassName(String packageName) {
        List<String> classNameList = new ArrayList<String>();
        try {
            DexFile df = new DexFile(BaseApplication.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);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return classNameList;
    }
}