Android自定义指令集处理框架

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

本文主要以这个例子说明:我要从某个网站下载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进行编码。

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容