編輯:關於 Android 程式設計
前面我們知道了,要生成.patch補丁文件,需要借助apkpatch這個工具。本章我們就來看看它內部的實現原理。apkpatch是一個並未開源的jar包,但借助JD-GUI或procyon反編譯,我們依然能讀到它的源碼(以1.0.3版本為例)。
在動手之前,有幾個「坑」必須先講清楚:
位於com.euler.patch包下,一切從Main()方法開始。
public static void main(String[] args) {
CommandLineParser parser = new PosixParser();
CommandLine commandLine = null;
option();
try {
commandLine = parser.parse(allOptions, args);
} catch (ParseException e) {
System.err.println(e.getMessage());
usage(commandLine);
return;
}
//第一部分:校驗必填參數
if ((!commandLine.hasOption('k')) && (!commandLine.hasOption("keystore"))) { usage(commandLine); return; }
if ((!commandLine.hasOption('p')) && (!commandLine.hasOption("kpassword"))) { usage(commandLine); return; }
if ((!commandLine.hasOption('a')) && (!commandLine.hasOption("alias"))) { usage(commandLine); return; }
if ((!commandLine.hasOption('e')) && (!commandLine.hasOption("epassword"))) { usage(commandLine); return; }
File out = null;
if ((!commandLine.hasOption('o')) && (!commandLine.hasOption("out"))) out = new File("");
else out = new File(commandLine.getOptionValue('o'));
//第二部分:讀取簽名相關參數
String keystore = commandLine.getOptionValue('k');
String password = commandLine.getOptionValue('p');
String alias = commandLine.getOptionValue('a');
String entry = commandLine.getOptionValue('e');
String name = "main";
if ((commandLine.hasOption('n')) || (commandLine.hasOption("name"))) {
name = commandLine.getOptionValue('n');
}
if ((commandLine.hasOption('m')) || (commandLine.hasOption("merge"))) {
//合併多個補丁的分支
String[] merges = commandLine.getOptionValues('m');
File[] files = new File[merges.length];
for (int i = 0; i < merges.length; i++) {
files[i] = new File(merges[i]);
}
MergePatch mergePatch = new MergePatch(files, name, out, keystore, password, alias, entry);
mergePatch.doMerge();
} else {
//常規打補丁分支
if ((!commandLine.hasOption('f')) && (!commandLine.hasOption("from"))) { usage(commandLine); return; }
if ((!commandLine.hasOption('t')) && (!commandLine.hasOption("to"))) { usage(commandLine); return; }
File from = new File(commandLine.getOptionValue("f"));
File to = new File(commandLine.getOptionValue('t'));
if ((!commandLine.hasOption('n')) && (!commandLine.hasOption("name"))) {
name = from.getName().split("\\.")[0];
}
//第三部分:構建ApkPatch並執行
ApkPatch apkPatch = new ApkPatch(from, to, name, out, keystore, password, alias, entry);
apkPatch.doPatch();
}
}
這段代碼可以切成幾塊來看:第一部分檢查命令行必填參數,缺參數就打印用法提示;第二部分讀取正式打包時用到的keystore、password、alias、entry等參數;第三部分把這些參數交給ApkPatch構造函數初始化,最後調用doPatch()開工。
public ApkPatch(File from, File to, String name, File out, String keystore, String password, String alias, String entry) {
super(name, out, keystore, password, alias, entry);
this.from = from;
this.to = to;
}
它調用了父類Build的構造函數,做的事很簡單——給變量賦值。若out不存在,父類會自動創建這個輸出目錄。
protected static final String SUFFIX = ".apatch";
protected String name;
private String keystore;
private String password;
private String alias;
private String entry;
protected File out;
public Build(String name, File out, String keystore, String password, String alias, String entry) {
this.name = name;
this.out = out;
this.keystore = keystore;
this.password = password;
this.alias = alias;
this.entry = entry;
if (!out.exists()) out.mkdirs();
else if (!out.isDirectory()) throw new RuntimeException("output path must be directory.");
}
一句話概括就是兩步:先對比兩個apk拿到差異,再把結果打包成apatch文件。
public void doPatch() {
try {
final File smaliDir = new File(this.out, "smali");
if (!smaliDir.exists()) smaliDir.mkdir();
final File dexFile = new File(this.out, "diff.dex");
final File outFile = new File(this.out, "diff.apatch");
//第一步:對比兩個apk,差異寫入DiffInfo
final DiffInfo info = new DexDiffer().diff(this.from, this.to);
//第二步:把差異寫成smali,再打包成dex
this.classes = buildCode(smaliDir, dexFile, info);
//第三步:把dex寫入jar並簽名,生成diff.apatch
this.build(outFile, dexFile);
//第四步:重命名收尾
this.release(this.out, dexFile, outFile);
} catch (Exception e2) {
e2.printStackTrace();
}
}
public DiffInfo diff(final File newFile, final File oldFile) throws IOException {
final DexBackedDexFile newDexFile = DexFileFactory.loadDexFile(newFile, 19, true);
final DexBackedDexFile oldDexFile = DexFileFactory.loadDexFile(oldFile, 19, true);
final DiffInfo info = DiffInfo.getInstance();
boolean contains = false;
for (final DexBackedClassDef newClazz : newDexFile.getClasses()) {//遍歷新apk所有類
final Set<? extends DexBackedClassDef> oldclasses = oldDexFile.getClasses();
for (final DexBackedClassDef oldClazz : oldclasses) {//遍歷舊apk所有類
if (newClazz.equals(oldClazz)) {//同名類,記錄修改
this.compareField(newClazz, oldClazz, info);
this.compareMethod(newClazz, oldClazz, info);
contains = true;
break;
}
}
if (!contains) {//否則記錄為新增類
info.addAddedClasses(newClazz);
}
}
return info;
}
其中提取dex的地方在DexFileFactory類裡。可以看到它只取出了classes.dex,這正是原生工具不支持multidex的根源。
public static DexBackedDexFile loadDexFile(File dexFile, int api, boolean experimental) throws IOException {
return loadDexFile(dexFile, "classes.dex", new Opcodes(api, experimental));
}
對比變量的compareField——再次印證了AndFix不支持新增或修改成員變量:
public void compareField(DexBackedField object, Iterable<? extends DexBackedField> olds, DiffInfo info) {
for (DexBackedField reference : olds) {
if (reference.equals(object)) {
if ((reference.getInitialValue() == null) && (object.getInitialValue() != null)) { info.addModifiedFields(object); return; }
if ((reference.getInitialValue() != null) && (object.getInitialValue() == null)) { info.addModifiedFields(object); return; }
if ((reference.getInitialValue() == null) && (object.getInitialValue() == null)) { return; }
if (reference.getInitialValue().compareTo(object.getInitialValue()) != 0) { info.addModifiedFields(object); return; }
return;
}
}
info.addAddedFields(object);
}
對比方法的compareMethod——同名不同實現記錄為修改,名字不同記錄為新增:
public void compareMethod(DexBackedMethod object, Iterable<? extends DexBackedMethod> olds, DiffInfo info) {
for (DexBackedMethod reference : olds) {
if (reference.equals(object)) {
if ((reference.getImplementation() == null) && (object.getImplementation() != null)) { info.addModifiedMethods(object); return; }
if ((reference.getImplementation() != null) && (object.getImplementation() == null)) { info.addModifiedMethods(object); return; }
if ((reference.getImplementation() == null) && (object.getImplementation() == null)) { return; }
if (!reference.getImplementation().equals(object.getImplementation())) { info.addModifiedMethods(object); return; }
return;
}
}
info.addAddedMethods(object);
}
把上一步的diff信息寫成smali文件,並生成diff.dex。smali文件以_CF.smali結尾,並在修改處用自定義註解MethodReplace標注,供替換階段查找待修復的變量或方法。
private static Set buildCode(final File smaliDir, final File dexFile, final DiffInfo info) throws IOException, RecognitionException, FileNotFoundException {
final ClassFileNameHandler outFileNameHandler = new ClassFileNameHandler(smaliDir, ".smali");
final ClassFileNameHandler inFileNameHandler = new ClassFileNameHandler(smaliDir, ".smali");
final DexBuilder dexBuilder = DexBuilder.makeDexBuilder();
for (final DexBackedClassDef classDef : list) {
final String className = classDef.getType();
baksmali.disassembleClass(classDef, outFileNameHandler, options);
final File smaliFile = inFileNameHandler.getUniqueFilenameForClass(TypeGenUtil.newType(className));
classes.add(TypeGenUtil.newType(className).substring(1, TypeGenUtil.newType(className).length() - 1).replace('/', '.'));
SmaliMod.assembleSmaliFile(smaliFile, dexBuilder, true, true);
}
dexBuilder.writeTo(new FileDataStore(dexFile));
return classes;
}
先從keystore取到應用簽名,實例化PatchBuilder並調用writeMeta(getMeta()),把Manifest寫入META-INF/PATCH.MF,再通過sealPatch把dex與簽名信息封入其中。
protected void build(File outFile, File dexFile) throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
KeyStore.PrivateKeyEntry privateKeyEntry = null;
InputStream is = new FileInputStream(this.keystore);
keyStore.load(is, this.password.toCharArray());
privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(this.alias, new KeyStore.PasswordProtection(this.entry.toCharArray()));
PatchBuilder builder = new PatchBuilder(outFile, dexFile, privateKeyEntry, System.out);
builder.writeMeta(getMeta());
builder.sealPatch();
}
getMeta()負責組裝寫入清單的內容:
protected Manifest getMeta() {
Manifest manifest = new Manifest();
Attributes main = manifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
main.putValue("Created-By", "1.0 (ApkPatch)");
main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString());
main.putValue("From-File", this.from.getName());
main.putValue("To-File", this.to.getName());
main.putValue("Patch-Name", this.name);
main.putValue("Patch-Classes", Formater.dotStringList(this.classes));
return manifest;
}
最後一步,對dexFile做MD5,再把outFile重命名為帶MD5的.apatch文件。看到「.apatch」有沒有很激動?我們的補丁包就是這樣誕生的。
protected void release(File outDir, File dexFile, File outFile) throws NoSuchAlgorithmException, FileNotFoundException, IOException {
MessageDigest messageDigest = MessageDigest.getInstance("md5");
FileInputStream fileInputStream = new FileInputStream(dexFile);
byte[] buffer = new byte[8192];
int len = 0;
while ((len = fileInputStream.read(buffer)) > 0) {
messageDigest.update(buffer, 0, len);
}
String md5 = HexUtil.hex(messageDigest.digest());
fileInputStream.close();
outFile.renameTo(new File(outDir, this.name + "-" + md5 + ".apatch"));
}
Android 進階實戰:RecyclerView 與 CardView 綜合運用
CardView 添加依賴:在 Android Studio 中搜索 cardview 即可,位於 V7 包中;也可以直接在 gradle 裡添加: compile co
從零開始學 Android:Intent 進階用法(四十一)
上一節我們學會了 Intent 的基本用法——在多個 Activity 之間跳轉並傳遞資料。這一節要讓 Intent 做一些更實際的事:開啟網頁、撥打電話、寄送簡訊。這些
Android ListView 靜態資料設定完整教學
有些時候,ListView 只需要呈現固定資料,不必從網路或資料庫動態取得。本文示範如何以靜態陣列建立圖文列表,並透過自訂 Adapter 完成顯示。 版面設計 主頁面
SqlBrite 入門:給原生 SQLite 裝上響應式引擎
有句老話是這麼說的:除非迫不得已,不然別在 App 裡擼數據庫。不過需求真來了,躲也躲不掉。 Android 平台上的 ORM 框架多到眼花,GreenDao 算是老牌選