Android 自定义指令集处理框架

516 阅读4分钟

有这样一种需求,从服务器或者某些地方获取一些指令,我们去处理这些指令,比方说打开某个界面,浏览某些网页,下载某个文件等。

本文主要以这个例子说明:我要从某个网站下载QQ APK安装到手机,那么我下载的是XX应用市场,然后安装市场完他会去下载我想要的QQ 安装包。那么,应用市场是怎么知道的呢?
下面,我们就引入指令处理框架:

上述问题,我们只要从应用市场的APK包里面获取相应的指令,使用我们指令处理框架进行处理就好了。就是那么简单。

  • 我们的指令存放在哪里?
    首先我们知道APK安装包就是一个压缩文件,(我们给APK的后缀改成rar就能进行解压)那么我们可以对这个压缩文件添加一些附加信息。这样我们在下载apk的时候,就会把相应的指令添加在应用市场apk的压缩包里面。
  • 获取并处理指令:
    1、首先我们得得到应用市场的apk路径地址。
    public static String getMyAPkPath(Context context) {
      if (context == null) {
          return null;
      }    
    String installAPKPath = "";
      String packageName = context.getPackageName();
      try {
          installAPKPath = context.getPackageManager().getApplicationInfo(
                  packageName, PackageManager.GET_UNINSTALLED_PACKAGES).sourceDir;
      } catch (PackageManager.NameNotFoundException e) { 
         e.printStackTrace(); 
     } 
     return installAPKPath;
    }
    第二部我们从该压缩包得到我们的额外信息:
    public static String extractZipComment(String filename) {
       String retStr = null;
       try {
           File file = new File(filename);
           int fileLen = (int) file.length();
           FileInputStream in = new FileInputStream(file);
    /* The whole ZIP comment (including the magic byte sequence)
           * MUST fit in the buffer* otherwise, the comment will not be recognized correctly** You can safely increase the buffer size if you like*/
           byte[] buffer = new byte[Math.min(fileLen, 8192)]; 
          int len;
           in.skip(fileLen - buffer.length);
           if ((len = in.read(buffer)) > 0) {
               retStr = getZipCommentFromBuffer(buffer, len);
           } 
          in.close();
       } catch (Exception e) {
           e.printStackTrace(); 
      }
       return retStr;
    }
    另一个方法
    private static String getZipCommentFromBuffer(byte[] buffer, int len) {
      byte[] magicDirEnd = {0x50, 0x4b, 0x05, 0x06}; 
     int buffLen = Math.min(buffer.length, len);
      //Check the buffer from the end
      for (int i = buffLen - magicDirEnd.length - 22; i >= 0; i--) { 
         boolean isMagicStart = true;
          for (int k = 0; k < magicDirEnd.length; k++) {
              if (buffer[i + k] != magicDirEnd[k]) { 
                 isMagicStart = false;
                  break; 
             } 
         }
          if (isMagicStart) {
              //Magic Start found! 
             int commentLen = buffer[i + 20] + buffer[i + 22] * 256; 
             int realLen = buffLen - i - 22;
              log("ZIP comment found at buffer position " + (i + 22) + " with len=" + commentLen + ", good!");            
                 if (commentLen != realLen) { 
                 log("WARNING! ZIP comment size mismatch: directory says len is " +commentLen + ", but file ends after " + realLen + " bytes!"); 
                     } 
             String comment = new String(buffer, i + 22, Math.min(commentLen, realLen));
              return comment.trim();
          } 
     } 
     log("ERROR! ZIP comment NOT found!");
      return null;
    }
    该方法是得到应用市场apk安装包的额外信息,也就是原始指令集合。该例子是使用json数组实现指令集的。

下面我们开始构造指令集处理框架:

首先我们把处理指令的共有的方法抽象成一个接口,

public interface InstructionInterface {    
    List<String> getInstructionList(String data);
    boolean doInstructionList(Context context, List<String> orders);
}

然后定义一个管理类

public class InstructionManager {
    private static final String TAG = InstructionManager.class.getSimpleName();
    public static InstructionZIPImpl getZIPImpl() { 
       return new InstructionZIPImpl();
    }}

管理类我们能得到一个具体的实现类的对象,同时如果有其他类型的处理方式也会得到具体的处理类的对象,还可以进行优化。

现在我们看看具体的实现类:

public final class InstructionZIPImpl implements InstructionInterface { 
   private static final String TAG = InstructionZIPImpl.class.getSimpleName();
    public InstructionZIPImpl() {
    } 
   public String getComment(Context context) {
        if (context == null) { 
           return ""; 
       }
        String path = InstructionUtils.getMyAPkPath(context); 
       if (TextUtils.isEmpty(path)) {
            return "";
        } 
       return InstructionUtils.extractZipComment(path); 
   } 
   @Override
    public List<String> getInstructionList(String comment) { 
       List<String> orderLists = new ArrayList<>(); 
       if (!TextUtils.isEmpty(comment)) { 
           List<String> orders = JsonUtils.stringListFromJson(comment); 
           if (orders != null) {
                orderLists.addAll(orders); 
           } 
       } 
       return orderLists;
    }
    @Override 
   public boolean doInstructionList(Context context, List<String> orders) { 
       boolean isSuccess = true;
        if (context == null || orders == null || orders.size() <= 0) { 
           return false; 
       } 
       for (String order : orders) {
            boolean handleAction = Launcher.handleUriAction(context, Uri.parse(order)); 
           if (!handleAction) {
                isSuccess = false;
            } 
       } 
       return isSuccess; 
   }}

其中InstructionUtils就是包含我们开始定义的两个方法。
JsonUtils.stringListFromJson()是gson的方法,就是把string类型的json串实例化。
写代码的时候要注意程序的健壮性,避免输入错误数据不会造成我们方法内部崩溃。

我们把String类型命令集合转成我们需要的Uri类型的指令,下面是使用方法
也就是Launcher的方法

public static boolean handleUriAction(Context context, Uri uri) {
    if (uri == null)
        return false;
    String scheme = uri.getScheme();
    if ("my_order".equals(scheme)) { 
       String action = uri.getAuthority();
        if ("do_something".equals(action)) {
            doMyOrder(context, uri.getQueryParameter("my_data")); 
       } 
       return true; 
   } 
   return false;}private static void doMyOrder(Context context, String json) { 
   if (TextUtils.isEmpty(json)) {
        return;
    } 
   // TODO: 22/11/2016 we can do something with 'json'
    //使用json实例化,或者把需要的数据传递进来。就可以进行命令处理。
}

使用Uri我们很容易得到我们需要的东西。
上述代码我给一个使用例子,是三个指令的集合,我们只要对json进行解析就可以了

String testString = "[\"my_order://do_something/?my_data=\",\"my_order://do_something/?\",\"my_order://do_something/?\"]";

同样,我们从任何地方获取指令都可以进行处理,具体的实现就可以在doMyOrder进行编码。

本人程序界菜鸟一门,如有问题或者建议还望能批评指出。由于本文是框架类型,故源码没贴出来,不过文章写的很详细,所有的代码都在里面了。