自动化打包apk总结并整合资料 (继)

上次的总结已过了一段时间,这次细说当中的解析manifest模块 涉及到三块功能

# 一、解析manifest
# 二、maven生成JAR包
# 三、Ant执行调用解析方法

一、解析manifest

使用JAVA实现解析方法,并生成可执行jar包 最终通过shell命令执行解析动做,这里不做详细解释只贴出两部分代码 以做备忘。
1、做为外部使用shell命令的出口代码:
public class AndroidManifestRewriter {
    public static void main(String[] args) throws IOException {
        try{
            Args argList = Args.parseArgs(args);
        
            if(argList == null) {
                System.out.println( "java -jar axml-io.jar -i xxx -o xxx ...");
                System.exit(0);
            }

            new AndroidManifestRewriter().rewrite(new File(argList.mInManifest), new File(argList.mOutManifest), argList.mVersionCode, argList.mVersionName, argList.mChannelValue);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private void rewrite(File source, File target, String versionCode, String versionName, String channelValue) throws IOException {
        final AndroidManifest manifest = new AndroidManifest(source);
        System.out.println("Gefunden: versionName='" + manifest.getVersionName() + "', versionCode=" + manifest.getVersionCode() + ", "+ manifest.getChannelName() + ":" + manifest.getChannelValue() + "," + manifest.getChannelGTName() + ":" + manifest.getChannelGTValue());
        manifest.validate(source);
        if (versionName != null) {
            manifest.setVersionName(versionName);
        }
        if (versionCode != null) {
            manifest.setVersionCode(Integer.parseInt(versionCode));
        }
        if (channelValue != null) {
            manifest.setChannelValue(channelValue);
        }
        if (channelValue != null && manifest.getChannelGTName() != null){
            manifest.setChannelGTValue(channelValue);
        }
        System.out.println("Gefunden: versionName='" + manifest.getVersionName() + "', versionCode=" + manifest.getVersionCode() + ", "+ manifest.getChannelName() + ":" + manifest.getChannelValue() + "," + manifest.getChannelGTName() + ":" + manifest.getChannelGTValue());
        manifest.write(target);
    }

    static class Args {
        public String mInManifest = null;
        public String mOutManifest = null;
        public String mVersionCode = null;
        public String mVersionName = null;
        public String mChannelValue = null;

        public static Args parseArgs(String[] args) {
            Args argList = new Args();

            Options options = new Options();
            options.addOption("h", "help", false, "Print this usage information");
            options.addOption("i", "in", true, "Type a input AndroidManifest.xml file" );
            options.addOption("o", "out", true, "Type a output AndroidManifest.xml file" );
            options.addOption(null, "versionCode", true, "Modify android:versionCode by input value" );
            options.addOption(null, "versionName", true, "Modify android:versionName by input value" );
            options.addOption(null, "channelValue", true, "Modify meta-data:channelValue by input value" );

            CommandLineParser parser = new BasicParser();
            CommandLine commandLine = null;

            try {
                commandLine = parser.parse( options, args );
            } catch (ParseException ex) {
                System.err.println(ex.getMessage());
                System.out.println( "java -jar axml-io.jar -i xxx -o xxx ...");
                System.exit(0);
            }

            boolean cmdFound = false;
            if( commandLine.hasOption("h") ) {
                System.out.println( "java -jar axml-io.jar -i xxx -o xxx ...");
                System.exit(0);
            }
            if( commandLine.hasOption("i") ) {
                argList.mInManifest = commandLine.getOptionValue("i");
                cmdFound = true;
            }
            if( commandLine.hasOption("o") ) {
                argList.mOutManifest = commandLine.getOptionValue("o");
                cmdFound = true;
            }
            if( commandLine.hasOption("versionCode") ) {
                argList.mVersionCode = commandLine.getOptionValue("versionCode");
                cmdFound = true;
            }
            if( commandLine.hasOption("versionName") ) {
                argList.mVersionName = commandLine.getOptionValue("versionName");
                cmdFound = true;
            }
            if( commandLine.hasOption("channelValue") ) {
                argList.mChannelValue = commandLine.getOptionValue("channelValue");
                cmdFound = true;
            }

            if (cmdFound == false) {
                System.out.println( "java -jar axml-io.jar -i xxx -o xxx ...");
                System.exit(0);
            }

            return argList;
        }
    }
}

此处代码 将与maven生成所用到的 pom.xml相关,做为可执行jar包

2、解析后替换清单文件中相关的KEY-VALUE值,因为这次总结 主要源于打包后台需求有修改,不只使用友盟上报统计,又增加了个额外的统计SDK 他自有一套统计SDK,并有独立的meta 定义渠道名称,相应的 在解析时对渠道多了一个维度的修改,主要需要修改的代码如下:

AndroidManifest.java

private ResXmlAttribute(ResSource src) {
            this.namespace = new ResStringPoolRef(src);
            this.name = new ResStringPoolRef(src);
            this.rawValue = new ResStringPoolRef(src);
            this.typedValue = new ResValue(src);
            
            if ("http://schemas.android.com/apk/res/android".equals(this.namespace.lookup())) {
                if (-1 == versionCode && "versionCode".equals(name.lookup())) {
                    versionCode = typedValue.asInt();
                    isVersionCode = true;
                } else if (null == versionName && "versionName".equals(name.lookup())) {
                    versionName = typedValue.asString();
                    isVersionName = true;
                } else if (null == channelName && "UMENG_CHANNEL".equals(rawValue.lookup())) {
                    channelName = typedValue.asString();
                } else if (null == channelGTName && "GT_INSTALL_CHANNEL".equals(rawValue.lookup())) {
                    channelGTName = typedValue.asString();
                } else if (null == channelValue && null != channelName) {
                    channelValue = typedValue.asString();
                    isChannelValue = true;
                }else if (null == channelGTValue && null != channelGTName) {
                    channelGTValue = typedValue.asString();
                    isChannelGTValue = true;
                }
            }
        }

        public void writeTo(ResTarget tgt) {
            this.namespace.writeTo(tgt);
            this.name.writeTo(tgt);
            if (isVersionName && versionNameChanged) {
                long newIndex = stringPool.getIndexOfNewVersionName();
                this.rawValue.writeTo(tgt, newIndex);
                typedValue.writeToWithNewVersionIndex(tgt, newIndex);
            } else if (isVersionCode && versionCodeChanged) {
                this.rawValue.writeTo(tgt);
                typedValue.writeToWithNewVersionCode(tgt);
            } else if (isChannelValue && channelValueChanged) {
                long newIndex = stringPool.getIndexOfNewChannelValue();
                this.rawValue.writeTo(tgt, newIndex);
                System.out.println("getIndexOfNewChannelValue:"+newIndex);
                typedValue.writeToWithNewChannelIndex(tgt, newIndex);
            } else if (isChannelGTValue && channelValueChanged) {
                long newIndex = stringPool.getIndexOfNewChannelGTValue();
                this.rawValue.writeTo(tgt, newIndex);
                System.out.println("getIndexOfNewChannelGTValue:"+newIndex);
                typedValue.writeToWithNewChannelIndex(tgt, newIndex);
            } else {
                this.rawValue.writeTo(tgt);
                typedValue.writeTo(tgt);
            }
        }


AndroidManifestRewriter.java

    private void rewrite(File source, File target, String versionCode, String versionName, String channelValue) throws IOException {
        final AndroidManifest manifest = new AndroidManifest(source);
        System.out.println("Gefunden: versionName='" + manifest.getVersionName() + "', versionCode=" + manifest.getVersionCode() + ", "+ manifest.getChannelName() + ":" + manifest.getChannelValue() + "," + manifest.getChannelGTName() + ":" + manifest.getChannelGTValue());
        manifest.validate(source);
        if (versionName != null) {
            manifest.setVersionName(versionName);
        }
        if (versionCode != null) {
            manifest.setVersionCode(Integer.parseInt(versionCode));
        }
        if (channelValue != null) {
            manifest.setChannelValue(channelValue);
        }
        if (channelValue != null && manifest.getChannelGTName() != null){
            manifest.setChannelGTValue(channelValue);
        }
        System.out.println("Gefunden: versionName='" + manifest.getVersionName() + "', versionCode=" + manifest.getVersionCode() + ", "+ manifest.getChannelName() + ":" + manifest.getChannelValue() + "," + manifest.getChannelGTName() + ":" + manifest.getChannelGTValue());
        manifest.write(target);
    }

GT_INSTALL_CHANNEL 的增加 引起的channelGTName,channelGTValue,isChannelGTValue,getIndexOfNewChannelGTValue()一系列变量、方法的增加。

二、maven生成JAR包,

解析方法完成后,切换到 项目工程目录下,包含pom.xml文件的目录下

image.png

执行命令:mvn assembly:assembly 会生成可执行JAR包。
关于pom.xml有两处需要注意下 XML文件如下

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>idotools</groupId>
    <artifactId>axml-io</artifactId>
    <version>1.0.2</version>

    <dependencies>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>  
<!--                <artifactId>maven-jar-plugin</artifactId>  -->
                <artifactId>maven-assembly-plugin</artifactId>  
                <configuration>  
                    <archive>  
                        <manifest>  
                            <addClasspath>true</addClasspath>  
                            <classpathPrefix>libs/</classpathPrefix>  
                            <mainClass>idotools.axml.io.AndroidManifestRewriter</mainClass>
                        </manifest>  
                    </archive>  
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>  
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>  
        </plugins>
    </build>
</project>

其中
<version>1.0.2</version> 代表JAR的版本号;
<mainClass>idotools.axml.io.AndroidManifestRewriter</mainClass> 代表可执行入口类名称。
就此 解析方法修改完成,接下来实现使用ant 在build.xml中配置此可执行jar包,实现批量打包。

三、Ant执行调用解析方法

    <target name="change-channel" if="has.channel" >
        <echo level="info">New Channel umeng: ${CHANNEL}</echo>
        <exec dir="${apk.obj.dir}" executable="${utils.dir}/axmlio" >
            <arg value="-i" />
            <arg value="${apk.obj.dir}/AndroidManifest.xml" />
            <arg value="-o" />
            <arg value="${apk.obj.dir}/AndroidManifest.xml.tmp" />
            <arg value="--channelValue" />
            <arg value="${CHANNEL}" />
        </exec>
        <move file="${apk.obj.dir}/AndroidManifest.xml.tmp" tofile="${apk.obj.dir}/AndroidManifest.xml" overwrite="true" />
    </target>

以上是build.xml中对渠道的替换配置,可以见到 执行axmlio shell命令,其中参数 -i -o --channelValue 与可执行JAR中的AndroidManifestRewriter相关。以下只做参考

    static class Args {
        public String mInManifest = null;
        public String mOutManifest = null;
        public String mVersionCode = null;
        public String mVersionName = null;
        public String mChannelValue = null;

        public static Args parseArgs(String[] args) {
            Args argList = new Args();

            Options options = new Options();
            options.addOption("h", "help", false, "Print this usage information");
            options.addOption("i", "in", true, "Type a input AndroidManifest.xml file" );
            options.addOption("o", "out", true, "Type a output AndroidManifest.xml file" );
            options.addOption(null, "versionCode", true, "Modify android:versionCode by input value" );
            options.addOption(null, "versionName", true, "Modify android:versionName by input value" );
            options.addOption(null, "channelValue", true, "Modify meta-data:channelValue by input value" );

            CommandLineParser parser = new BasicParser();
            CommandLine commandLine = null;

            try {
                commandLine = parser.parse( options, args );
            } catch (ParseException ex) {
                System.err.println(ex.getMessage());
                System.out.println( "java -jar axml-io.jar -i xxx -o xxx ...");
                System.exit(0);
            }

            boolean cmdFound = false;
            if( commandLine.hasOption("h") ) {
                System.out.println( "java -jar axml-io.jar -i xxx -o xxx ...");
                System.exit(0);
            }
......
}

也可以切换到utils下执行

./axmlio -i AndroidManifest.xm -o AndroidManifest.xml.tmp --channelValue mumay

shell 文件axmlio 内容如下:

#!/bin/bash
#
# Copyright (C) 2007 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script is a wrapper for smali.jar, so you can simply call "smali",
# instead of java -jar smali.jar. It is heavily based on the "dx" script
# from the Android SDK

# Set up prog to be the path of this script, including following symlinks,
# and set up progdir to be the fully-qualified pathname of its directory.
prog="$0"
while [ -h "${prog}" ]; do
    newProg=`/bin/ls -ld "${prog}"`
    echo ${newProg}


    newProg=`expr "${newProg}" : ".* -> \(.*\)$"`
    if expr "x${newProg}" : 'x/' >/dev/null; then
        prog="${newProg}"
    else
        progdir=`dirname "${prog}"`
        prog="${progdir}/${newProg}"
    fi
done
oldwd=`pwd`
progdir=`dirname "${prog}"`
cd "${progdir}"
progdir=`pwd`
prog="${progdir}"/`basename "${prog}"`
cd "${oldwd}"


jarfile=axmlio.jar
libdir="$progdir"
if [ ! -r "$libdir/$jarfile" ]
then
    echo `basename "$prog"`": can't find $jarfile"
    exit 1
fi

javaOpts=""

# If you want DX to have more memory when executing, uncomment the following
# line and adjust the value accordingly. Use "java -X" for a list of options
# you can pass here.
# 
javaOpts="-Xmx512M"

# Alternatively, this will extract any parameter "-Jxxx" from the command line
# and pass them to Java (instead of to dx). This makes it possible for you to
# add a command-line parameter such as "-JXmx256M" in your ant scripts, for
# example.
while expr "x$1" : 'x-J' >/dev/null; do
    opt=`expr "$1" : '-J\(.*\)'`
    javaOpts="${javaOpts} -${opt}"
    shift
done

if [ "$OSTYPE" = "cygwin" ] ; then
    jarpath=`cygpath -w  "$libdir/$jarfile"`
else
    jarpath="$libdir/$jarfile"
fi

# add current location to path for aapt
PATH=$PATH:`pwd`;
export PATH;
exec java $javaOpts -jar "$jarpath" "$@"

``

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

推荐阅读更多精彩内容