Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> 一個使用命令行編譯Android項目的工具類

一個使用命令行編譯Android項目的工具類

編輯:關於android開發

一個使用命令行編譯Android項目的工具類


一個使用命令行編譯Android項目的工具類

簡介

編譯apk項目需要使用的幾個工具,基本都在sdk中,它們分別是(Windows系統):

1.aapt.exe
資源打包工具 2.android.jar
Android編譯工具 3.dx.bat
dex文件生成工具 4.sdklib.jar
生成apk 5.jarsigner
簽名工具

准備

在打包前,需要的環境如下:
1.JDK1.6+
2.Android SDK
3.上述5個工具的路徑

打包過程

1.生成R.java文件
比如:

aapt package -f -m -J ./gen -S res -M AndroidManifest.xml -I D:\android_sdk_for_studio\platforms\android-22\android.jar

2.清空bin目錄
清空上次生成的文件
3.編譯java文件和jar包

javac -encoding GBK -target 1.5 -bootclasspath D:\android_sdk_for_studio\platforms\android-22\android.jar -d bin src\net\mobctrl\normal\apk\*.java gen\net\mobctrl\normal\apk\R.java -classpath libs\*.jar

4.使用dx工具打包成classes.dex

dx --dex --output=C:\Users\mochuan.zhb\newworkspace\BundleApk5\bin\classes.dex C:\Users\mochuan.zhb\newworkspace\BundleApk5\bin\

5.編譯成資源文件

aapt package -f -M AndroidManifest.xml -S res -I D:\android_sdk_for_studio\platforms\android-22\android.jar -F bin\resources.ap_ --non-constant-id

6.使用sdklib.jar工具生成未簽名的apk

java -cp D:\android_sdk_for_studio\tools\lib\sdklib.jar com.android.sdklib.build.ApkBuilderMain bin\MyCommond.apk -v -u -z bin\resources.ap_ -f bin\classes.dex -rf C:\Users\mochuan.zhb\newworkspace\BundleApk5\src

7.使用jarsigner對apk進行簽名
jarsigner -verbose -keystore C:\test.keystore -storepass 123456 -keypass 123456 -signedjar C:\projectdemo-signed.apk C:\test.apk test
 

BuildApkUtils源碼,自動生成命令並執行

package com.taobao.trip;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @Author Zheng Haibo (mochuan)
 * @Company Alibaba Group
 * @PersonalWebsite http://www.mobctrl.net
 * @version $Id: BuildUtils.java, v 0.1 2016年1月8日 下午8:47:42 mochuan.zhb Exp $
 * @Description 在Windows平台,如何使用命令行編譯android項目
 */
public class BuildApkUtils {

    private static final String ANDROID_JAR_PATH = "D:\\android_sdk_for_studio\\platforms\\android-22\\android.jar";

    private static final String AAPT_PATH = "D:\\mochuan.zhb\\android-sdks\\build-tools\\22.0.1\\aapt_alitrip.exe";

    private static final String DX_PATH = "D:\\android_sdk_for_studio\\build-tools\\22.0.1\\dx.bat";

    private static final String SDK_LIB_JAR_PATH = "D:\\android_sdk_for_studio\\tools\\lib\\sdklib.jar";

    private static final String batchDir = System.getProperty("user.dir")
            + "\\batch\\";

    private String projectDir;
    private int packageId = 127;

    public BuildApkUtils() {

    }

    public BuildApkUtils(String projectDir) {
        this.projectDir = projectDir;
    }

    public BuildApkUtils(String projectDir, int packageId) {
        this.projectDir = projectDir;
        this.packageId = packageId;
    }

    public void buildUnsingedApk() {
        clearDir(batchDir);
        clearDir(projectDir + "\\bin");
        generateR(projectDir, packageId);
        compileJavaFiles(projectDir);
        buildDexFile(projectDir);
        complieResources(projectDir, packageId);
        buildUnsignedApk(projectDir, "unsigned.apk");
        mergeExeBatchFiles();
    }

    /**
     * 第一步:產生R文件
     * 
     * @param projectDir
     * @param packageId
     */
    private static void generateR(String projectDir, int packageId) {
        StringBuffer command = new StringBuffer();
        command.append(AAPT_PATH).append(" package -f -m -J ")
                .append(projectDir).append("\\gen ").append("-S ")
                .append(projectDir).append("\\res ").append("-M ")
                .append(projectDir).append("\\AndroidManifest.xml ")
                .append(" -A ").append(projectDir).append("\\assets ")
                .append("-I ").append(ANDROID_JAR_PATH)
                .append(" --non-constant-id -x --package-id ")
                .append(packageId);
        buildExeBatchFiles(command.toString(), "1.bat");
    }

    /**
     * 編譯java文件
     * 
     * @param projectDir
     */
    private static void compileJavaFiles(String projectDir) {
        StringBuffer command = new StringBuffer();
        command.append("javac -target 1.5 -bootclasspath ")
                .append(ANDROID_JAR_PATH).append(" -d ").append(projectDir)
                .append("\\bin ");
        List javaFilePaths = new ArrayList();
        findJavaFiles(projectDir + "\\src", javaFilePaths);
        findJavaFiles(projectDir + "\\gen", javaFilePaths);
        for (String javaPath : javaFilePaths) {
            command.append(javaPath).append(" ");
        }
        command.append("-classpath ").append(projectDir)
                .append("\\libs\\.*jar");
        buildExeBatchFiles(command.toString(), "2.bat");
    }

    /**
     * 創建dex文件
     * 
     * @param projectDir
     */
    private static void buildDexFile(String projectDir) {
        StringBuffer command = new StringBuffer();
        command.append(DX_PATH).append(" --dex --output=").append(projectDir)
                .append("\\bin\\classes.dex").append(" ").append(projectDir)
                .append("\\bin");
        buildExeBatchFiles(command.toString(), "3.bat");
    }

    /**
     * 編譯資源文件
     * 
     * @param projectDir
     */
    private static void complieResources(String projectDir, int packageId) {
        StringBuffer command = new StringBuffer();
        command.append(AAPT_PATH).append(" package -f -M ").append(projectDir)
                .append("\\AndroidManifest.xml ").append("-S ")
                .append(projectDir).append("\\res ").append("-I ")
                .append(ANDROID_JAR_PATH).append(" -A ").append(projectDir)
                .append("\\assets ").append(" -F ").append(projectDir)
                .append("\\bin\\resources.ap_")
                .append(" --non-constant-id -x --package-id ")
                .append(packageId);
        buildExeBatchFiles(command.toString(), "4.bat");
    }

    /**
     * 生成未簽名的apk
     * 
     * @param projectDir
     * @param apkName
     */
    private static void buildUnsignedApk(String projectDir, String apkName) {
        StringBuffer command = new StringBuffer();
        command.append("java -cp ").append(SDK_LIB_JAR_PATH)
                .append(" com.android.sdklib.build.ApkBuilderMain ")
                .append(projectDir).append("\\bin\\").append(apkName)
                .append(" -v -u -z ").append(projectDir)
                .append("\\bin\\resources.ap_").append(" -f ")
                .append(projectDir).append("\\bin\\classes.dex")
                .append(" -rf ").append(projectDir).append("\\src");
        buildExeBatchFiles(command.toString(), "5.bat");
    }

    /**
     * 遞歸查找
     * 
     * @param projectDir
     * @param javaFilePaths
     */
    private static void findJavaFiles(String projectDir,
            List javaFilePaths) {
        File file = new File(projectDir);
        File[] files = file.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                findJavaFiles(f.getAbsolutePath(), javaFilePaths);
            } else {
                if (f.getAbsolutePath().endsWith(".java")) {
                    javaFilePaths.add(f.getAbsolutePath());
                }
            }
        }
    }

    /**
     * 清理目錄
     * 
     * @param projectDir
     */
    private static void clearDir(String projectDir) {
        File file = new File(projectDir);
        File[] files = file.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                clearDir(f.getAbsolutePath());
            } else {
                f.delete();
            }
        }
    }

    /**
     * 創建批處理文件
     * 
     * @param command
     * @param file
     */
    private static void buildExeBatchFiles(String command, String fileName) {
        System.out.println(command);
        if (!new File(batchDir).exists()) {
            new File(batchDir).mkdirs();
        }
        String filePath = batchDir + fileName;
        try {
            writeFile(filePath, command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void mergeExeBatchFiles() {
        File file = new File(batchDir);
        System.out.println("debug:current path = " + file.getAbsolutePath());
        File[] files = file.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        Arrays.sort(files, new Comparator() {
            public int compare(File file1, File file2) {
                if (file1.lastModified() > file2.lastModified()) {
                    return 1;
                } else if (file1.lastModified() < file2.lastModified()) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        StringBuffer command = new StringBuffer();
        for (File f : files) {
            command.append("call ").append(f.getAbsolutePath()).append("\n");
        }
        try {
            String filePath = batchDir + "build.bat";
            writeFile(filePath, command.toString());
            Runtime.getRuntime().exec("cmd /c start " + filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 寫文件
     * 
     * @param filePath
     * @param sets
     * @throws IOException
     */
    private static void writeFile(String filePath, String content)
            throws IOException {
        FileWriter fw = new FileWriter(filePath);
        PrintWriter out = new PrintWriter(fw);
        out.write(content);
        out.println();
        fw.close();
        out.close();
    }

}

使用

運行的時候,我們只需要傳入項目路徑即可:


public class BuildMain {

    private static final String PROJECT_PATH = "C:\\Users\\mochuan.zhb\\newworkspace\\BundleApk5";

    private static final int PACKAGE_ID = 5;

    public static void main(String[] args) {
        new BuildApkUtils(PROJECT_PATH, PACKAGE_ID).buildUnsingedApk();
    }

}

運行過程中,會將生成的命令打印出來:


D:\mochuan.zhb\android-sdks\build-tools\22.0.1\aapt_alitrip.exe package -f -m -J C:\Users\mochuan.zhb\newworkspace\BundleApk5\gen -S C:\Users\mochuan.zhb\newworkspace\BundleApk5\res -M C:\Users\mochuan.zhb\newworkspace\BundleApk5\AndroidManifest.xml  -A C:\Users\mochuan.zhb\newworkspace\BundleApk5\assets -I D:\android_sdk_for_studio\platforms\android-22\android.jar --non-constant-id -x --package-id 5
javac -target 1.5 -bootclasspath D:\android_sdk_for_studio\platforms\android-22\android.jar -d C:\Users\mochuan.zhb\newworkspace\BundleApk5\bin C:\Users\mochuan.zhb\newworkspace\BundleApk5\src\net\mobctrl\normal\apk\BaseActivity.java C:\Users\mochuan.zhb\newworkspace\BundleApk5\src\net\mobctrl\normal\apk\BundleActivity.java C:\Users\mochuan.zhb\newworkspace\BundleApk5\src\net\mobctrl\normal\apk\FileUtils.java C:\Users\mochuan.zhb\newworkspace\BundleApk5\src\net\mobctrl\normal\apk\Utils.java C:\Users\mochuan.zhb\newworkspace\BundleApk5\gen\net\mobctrl\normal\apk\BuildConfig.java C:\Users\mochuan.zhb\newworkspace\BundleApk5\gen\net\mobctrl\normal\apk\R.java -classpath C:\Users\mochuan.zhb\newworkspace\BundleApk5\libs\.*jar
D:\android_sdk_for_studio\build-tools\22.0.1\dx.bat --dex --output=C:\Users\mochuan.zhb\newworkspace\BundleApk5\bin\classes.dex C:\Users\mochuan.zhb\newworkspace\BundleApk5\bin
D:\mochuan.zhb\android-sdks\build-tools\22.0.1\aapt_alitrip.exe package -f -M C:\Users\mochuan.zhb\newworkspace\BundleApk5\AndroidManifest.xml -S C:\Users\mochuan.zhb\newworkspace\BundleApk5\res -I D:\android_sdk_for_studio\platforms\android-22\android.jar -A C:\Users\mochuan.zhb\newworkspace\BundleApk5\assets  -F C:\Users\mochuan.zhb\newworkspace\BundleApk5\bin\resources.ap_ --non-constant-id -x --package-id 5
java -cp D:\android_sdk_for_studio\tools\lib\sdklib.jar com.android.sdklib.build.ApkBuilderMain C:\Users\mochuan.zhb\newworkspace\BundleApk5\bin\unsigned.apk -v -u -z C:\Users\mochuan.zhb\newworkspace\BundleApk5\bin\resources.ap_ -f C:\Users\mochuan.zhb\newworkspace\BundleApk5\bin\classes.dex -rf C:\Users\mochuan.zhb\newworkspace\BundleApk5\src

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved