編輯:關於 Android 程式設計
先簡單介紹一下 Instant Run。它是 Android Studio 2.0 之後新增的一種執行機制,能顯著縮短你第二次及之後的建置與部署時間。通俗地說,當你在 Android Studio 中修改了程式碼,Instant Run 能讓你很快看到修改後的效果;而在它問世之前,哪怕只是一個小小的改動,也可能需要等待幾十秒甚至更久才能看到結果。

建置整個 apk → 部署 app → app 重啟 → 重啟 Activity
而 Instant Run 則只需更少的時間。

只建置修改的部分 → 部署修改的 dex 或資源 → 熱部署、溫部署、冷部署
增量式程式碼變更會被套用並反映到 app 中,無需重啟 app,甚至不必重啟當前 Activity。適用於方法實作內的大多數簡單修改。
也就是說,方法內的簡單修改,無需重啟 app 和 Activity。
需要重啟 Activity 才能看到變更生效。通常用於資源的修改。
也就是說,app 無需重啟,但 Activity 需要重啟,例如資源的修改。
需要重啟 app(但仍不需重新安裝)。任何結構性變更都需要它,例如繼承關係或方法簽名的改變。
也就是說,app 需要重啟,例如繼承關係改變或方法簽名變化的情況。
講了這麼多概念,相信大家對 Instant Run 已有大體的認知。那麼它的實作原理究竟是什麼呢?其實在還沒看案例之前,我就大致能猜到 Instant Run 的思路——基於目前相當火紅的插件化框架,理解起來並不困難。但 Instant Run 畢竟是 Google 官方工具,仍具有很好的借鑒意義。
新建一個簡單的 Android Studio 專案,建立自己的 MyApplication,並在 AndroidManifest 檔中設定:
首先,我們先反編譯一下 APK 的構成:
使用的工具:d2j-dex2jar 和 jd-gui

裡面有 2 個 dex 文件和一個 instant-run.zip 文件。先分別看看兩個 dex 文件的源碼:
classes.dex 反編譯後的源碼:

裡面只有一個 AppInfo,保存了 app 的基本資訊,主要包含包名和 applicationClass。
classes2.dex 反編譯後的源碼:

我們赫然發現,兩個 dex 中竟然沒有一句我們自己寫的程式碼?那麼程式碼在哪裡呢?你可能猜到,app 真正的業務 dex 就在 instant-run.zip 中。解壓 instant-run.zip 之後,如下圖所示:

反編譯之後會發現,我們真正的業務程式碼都在這裡。
另外,我們再 decode 看一下 AndroidManifest 檔:

我們發現,我們的 application 也被替換了,替換成了 com.android.tools.fd.runtime.BootstrapApplication。
看到這裡,大體的思路就能猜到:
1. Instant-Run 程式碼作為一個宿主程式,將 app 作為資源 dex 加載起來,和插件化一個思路。
2. 那麼 Instant Run 是怎麼把業務程式碼運行起來的呢?
首先分析 BootstrapApplication,按照執行順序,依次分析 attachBaseContext 和 onCreate 方法。
protected void attachBaseContext(Context context) { if (!AppInfo.usingApkSplits) { String apkFile = context.getApplicationInfo().sourceDir; long apkModified = apkFile != null ? new File(apkFile).lastModified() : 0L; createResources(apkModified); setupClassLoaders(context, context.getCacheDir().getPath(), apkModified); } createRealApplication(); super.attachBaseContext(context); if (this.realApplication != null) { try { Method attachBaseContext = ContextWrapper.class.getDeclaredMethod("attachBaseContext", new Class[] { Context.class }); attachBaseContext.setAccessible(true); attachBaseContext.invoke(this.realApplication, new Object[] { context }); } catch (Exception e) { throw new IllegalStateException(e); } } }
我們依次需要關注的方法有:createResources → setupClassLoaders → createRealApplication → 調用 realApplication 的 attachBaseContext 方法。
private void createResources(long apkModified) { FileManager.checkInbox(); File file = FileManager.getExternalResourceFile(); this.externalResourcePath = (file != null ? file.getPath() : null); if (file != null) { try { long resourceModified = file.lastModified(); if ((apkModified == 0L) || (resourceModified <= apkModified)) { this.externalResourcePath = null; } } catch (Throwable t) { Log.e("InstantRun", "Failed to check patch timestamps", t); } } }
該方法主要是判斷資源 resource.ap_ 是否改變,然後保存 resource.ap_ 的路徑到 externalResourcePath 中。
private static void setupClassLoaders(Context context, String codeCacheDir, long apkModified) { List<String> dexList = FileManager.getDexList(context, apkModified); Class server = Server.class; Class patcher = MonkeyPatcher.class; if (!dexList.isEmpty()) { ClassLoader classLoader = BootstrapApplication.class.getClassLoader(); String nativeLibraryPath; try { nativeLibraryPath = (String) classLoader.getClass().getMethod("getLdLibraryPath", new Class[0]).invoke(classLoader, new Object[0]); } catch (Throwable t) { nativeLibraryPath = FileManager.getNativeLibraryFolder().getPath(); } IncrementalClassLoader.inject(classLoader, nativeLibraryPath, codeCacheDir, dexList); } }
繼續看 IncrementalClassLoader.inject 方法。IncrementalClassLoader 的源碼如下:
public class IncrementalClassLoader extends ClassLoader { private final DelegateClassLoader delegateClassLoader; public IncrementalClassLoader(ClassLoader original, String nativeLibraryPath, String codeCacheDir, List<String> dexes) { super(original.getParent()); this.delegateClassLoader = createDelegateClassLoader(nativeLibraryPath, codeCacheDir, dexes, original); } public Class findClass(String className) throws ClassNotFoundException { return this.delegateClassLoader.findClass(className); } private static class DelegateClassLoader extends BaseDexClassLoader { private DelegateClassLoader(String dexPath, File optimizedDirectory, String libraryPath, ClassLoader parent) { super(dexPath, optimizedDirectory, libraryPath, parent); } public Class findClass(String name) throws ClassNotFoundException { return super.findClass(name); } } private static DelegateClassLoader createDelegateClassLoader(String nativeLibraryPath, String codeCacheDir, List<String> dexes, ClassLoader original) { String pathBuilder = createDexPath(dexes); return new DelegateClassLoader(pathBuilder, new File(codeCacheDir), nativeLibraryPath, original); } public static ClassLoader inject(ClassLoader classLoader, String nativeLibraryPath, String codeCacheDir, List<String> dexes) { IncrementalClassLoader incrementalClassLoader = new IncrementalClassLoader(classLoader, nativeLibraryPath, codeCacheDir, dexes); setParent(classLoader, incrementalClassLoader); return incrementalClassLoader; } }
inject 方法用來設定 classloader 的父子順序,使用 IncrementalClassLoader 來加載 dex。由於 ClassLoader 的雙親委派模式(優先委託父類加載類,父類找不到再回本 ClassLoader 查找),調用之後的效果如下圖所示:

我們可以在 MyApplication 中用程式碼驗證一下:
@Override public void onCreate() { super.onCreate(); try{ String classLoaderName = getClassLoader().getClass().getName(); Log.d(TAG, "###onCreate in myApplication classLoaderName = " + classLoaderName); String parentClassLoaderName = getClassLoader().getParent().getClass().getName(); Log.d(TAG, "###onCreate in myApplication parentClassLoaderName = " + parentClassLoaderName); }catch (Exception e){ e.printStackTrace(); } }
運行結果:
... D/MyApplication: ###onCreate in myApplication classLoaderName = dalvik.system.PathClassLoader D/MyApplication: ###onCreate in myApplication parentClassLoaderName = com.android.tools.fd.runtime.IncrementalClassLoader
由此我們已經知道,當前 PathClassLoader 委託 IncrementalClassLoader 加載 dex。接著回到 BootstrapApplication 的 attachBaseContext 方法繼續分析。
private void createRealApplication() { if (AppInfo.applicationClass != null) { try { Class realClass = (Class) Class.forName(AppInfo.applicationClass); Constructor constructor = realClass.getConstructor(new Class[0]); this.realApplication = ((Application) constructor.newInstance(new Object[0])); } catch (Exception e) { throw new IllegalStateException(e); } } else { this.realApplication = new Application(); } }
該方法就是用 classes.dex 中的 AppInfo 類別的 applicationClass 常量中保存的 app 真實的 application。由上面的反編譯截圖可知,demo 中的 applicationClass 就是 mobctrl.net.testinstantrun.MyApplication。透過反射的方式,建立真正的 realApplication。
代理 realApplication 的生命週期,透過反射調用 realApplication 的 attachBaseContext 方法,以當前的 Context 為參數。attachBaseContext 方法執行結束之後,我們繼續往下看 BootstrapApplication 的 onCreate 方法。
public void onCreate() { if (!AppInfo.usingApkSplits) { MonkeyPatcher.monkeyPatchApplication(this, this, this.realApplication, this.externalResourcePath); MonkeyPatcher.monkeyPatchExistingResources(this, this.externalResourcePath, null); } else { MonkeyPatcher.monkeyPatchApplication(this, this, this.realApplication, null); } super.onCreate(); if (AppInfo.applicationId != null) { try { Server.create(AppInfo.applicationId, this); } catch (Throwable t) { Server.create(AppInfo.applicationId, this); } } if (this.realApplication != null) { this.realApplication.onCreate(); } }
我們依次需要關注的方法有:monkeyPatchApplication → monkeyPatchExistingResources → Server 啟動 → 調用 realApplication 的 onCreate 方法。
該方法的目的可以總結為:替換所有當前 app 的 application 為 realApplication。
public static void monkeyPatchApplication(Context context, Application bootstrap, Application realApplication, String externalResourceFile) { try { Class activityThread = Class.forName("android.app.ActivityThread"); Object currentActivityThread = getActivityThread(context, activityThread); Field mInitialApplication = activityThread.getDeclaredField("mInitialApplication"); mInitialApplication.setAccessible(true); Application initialApplication = (Application) mInitialApplication.get(currentActivityThread); if ((realApplication != null) && (initialApplication == bootstrap)) { mInitialApplication.set(currentActivityThread, realApplication); } if (realApplication != null) { Field mAllApplications = activityThread.getDeclaredField("mAllApplications"); mAllApplications.setAccessible(true); List allApplications = (List) mAllApplications.get(currentActivityThread); for (int i = 0; i < allApplications.size(); i++) { if (allApplications.get(i) == bootstrap) { allApplications.set(i, realApplication); } } } // 替換 mPackages、mResourcePackages 中的 LoadedApk 的 application ... } catch (Throwable e) { throw new IllegalStateException(e); } }
具體做的事情可以總結為:
替換所有當前 app 的 mAssets 為 newAssetManager。
public static void monkeyPatchExistingResources(Context context, String externalResourceFile, Collection activities) { if (externalResourceFile == null) { return; } try { AssetManager newAssetManager = (AssetManager) AssetManager.class.getConstructor(new Class[0]).newInstance(new Object[0]); Method mAddAssetPath = AssetManager.class.getDeclaredMethod("addAssetPath", new Class[] { String.class }); mAddAssetPath.setAccessible(true); mAddAssetPath.invoke(newAssetManager, new Object[] { externalResourceFile }); // 替換所有 Resource、Resource.Theme、Activity 中的 mAssets ... } catch (Throwable e) { throw new IllegalStateException(e); } }
該方法的目的總結為:
1. 如果 resource.ap_ 文件有改變,就建立一個 AssetManager 物件 newAssetManager,然後用 newAssetManager 替換所有當前 Resource、Resource.Theme 的 mAssets 成員變量。
2. 如果當前已經有 Activity 啟動了,還需要替換所有 Activity 中的 mAssets 成員變量。
判斷 Server 是否已經啟動,如果沒有啟動,則啟動 Server。
和 1.4 的目的相同,代理 realApplication 的生命週期。至此,我們的 app 就啟動起來了。下一步就要分析 Server 啟動之後,到底是如何進行熱部署、溫部署和冷部署的。
首先重點關注一下 Server 的內部類 SocketServerReplyThread。
private class SocketServerReplyThread extends Thread { private final LocalSocket mSocket; public void run() { try { DataInputStream input = new DataInputStream(this.mSocket.getInputStream()); DataOutputStream output = new DataOutputStream(this.mSocket.getOutputStream()); handle(input, output); } catch (IOException e) { } } private void handle(DataInputStream input, DataOutputStream output) throws IOException { long magic = input.readLong(); if (magic != 890269988L) { return; } int version = input.readInt(); output.writeInt(4); if (version == 4) { int message; for (;;) { message = input.readInt(); switch (message) { case 7: return; // EOF case 2: // Ping 回傳當前是否有前台 Activity break; case 3: // path-exists case 4: // checksum case 5: // 重啟 Activity break; case 1: // 接收 patch 列表 if (!authenticate(input)) { return; } List changes = ApplicationPatch.read(input); if (changes != null) { boolean hasResources = Server.hasResources(changes); int updateMode = input.readInt(); updateMode = Server.this.handlePatches(changes, hasResources, updateMode); boolean showToast = input.readBoolean(); output.writeBoolean(true); Server.this.restart(updateMode, hasResources, showToast); } break; case 6: // 顯示 Toast break; } } } } }
socket 開啟後,開始讀取數據,當讀到 1 時,取得程式碼變化的 ApplicationPatch 列表,然後調用 handlePatches 來處理程式碼的變化。
private int handlePatches(List changes, boolean hasResources, int updateMode) { if (hasResources) { FileManager.startUpdate(); } for (ApplicationPatch change : changes) { String path = change.getPath(); if (path.endsWith(".dex")) { handleColdSwapPatch(change); boolean canHotSwap = false; for (ApplicationPatch c : changes) { if (c.getPath().equals("classes.dex.3")) { canHotSwap = true; break; } } if (!canHotSwap) { updateMode = 3; } } else if (path.equals("classes.dex.3")) { updateMode = handleHotSwapPatch(updateMode, change); } else if (isResourcePath(path)) { updateMode = handleResourcePatch(updateMode, change, path); } } if (hasResources) { FileManager.finishUpdate(true); } return updateMode; }
1. 如果後綴為 “.dex”,冷部署處理 handleColdSwapPatch。
2. 如果後綴為 “classes.dex.3”,熱部署處理 handleHotSwapPatch。
3. 其他情況,溫部署,處理資源 handleResourcePatch。
private static void handleColdSwapPatch(ApplicationPatch patch) { if (patch.path.startsWith("slice-")) { File file = FileManager.writeDexShard(patch.getBytes(), patch.path); } }
把 dex 文件寫到私有目錄,等待整個 app 重啟,重啟之後,使用前面提到的 IncrementalClassLoader 加載 dex 即可。
private int handleHotSwapPatch(int updateMode, ApplicationPatch patch) { try { String dexFile = FileManager.writeTempDexFile(patch.getBytes()); if (dexFile == null) { return updateMode; } String nativeLibraryPath = FileManager.getNativeLibraryFolder().getPath(); DexClassLoader dexClassLoader = new DexClassLoader(dexFile, this.mApplication.getCacheDir().getPath(), nativeLibraryPath, getClass().getClassLoader()); Class aClass = Class.forName("com.android.tools.fd.runtime.AppPatchesLoaderImpl", true, dexClassLoader); PatchesLoader loader = (PatchesLoader) aClass.newInstance(); String[] getPatchedClasses = (String[]) aClass.getDeclaredMethod("getPatchedClasses", new Class[0]).invoke(loader, new Object[0]); if (!loader.load()) { updateMode = 3; } } catch (Exception e) { updateMode = 3; } return updateMode; }
將 patch 的 dex 文件寫入到臨時目錄,然後使用 DexClassLoader 去加載 dex,接著反射調用 AppPatchesLoaderImpl 類別的 load 方法。需要說明的是,AppPatchesLoaderImpl 繼承自抽象類 AbstractPatchesLoaderImpl,並實作了抽象方法 getPatchedClasses。如下是 AbstractPatchesLoaderImpl 抽象類的源碼,注意看 load 方法:
public abstract class AbstractPatchesLoaderImpl implements PatchesLoader { public abstract String[] getPatchedClasses(); public boolean load() { try { for (String className : getPatchedClasses()) { ClassLoader cl = getClass().getClassLoader(); Class aClass = cl.loadClass(className + "$override"); Object o = aClass.newInstance(); Class originalClass = cl.loadClass(className); Field changeField = originalClass.getDeclaredField("$change"); changeField.setAccessible(true); Object previous = changeField.get(null); if (previous != null) { Field isObsolete = previous.getClass().getDeclaredField("$obsolete"); if (isObsolete != null) { isObsolete.set(null, Boolean.valueOf(true)); } } changeField.set(null, o); } } catch (Exception e) { return false; } return true; } }
由此,我們大概理清了 Instant Run 熱部署的原理:
在第一次建置 apk 時,會在每一個類別中注入一個 $change 的成員變量,它實作了 IncrementalChange 介面,並在每一個方法中插入一段類似的邏輯。
IncrementalChange localIncrementalChange = $change; if (localIncrementalChange != null) { localIncrementalChange.access$dispatch("onCreate.(Landroid/os/Bundle;)V", new Object[] { this, ... }); return; }
也就是當 $change 不為空時,執行 IncrementalChange 中的方法。以 demo 的 MainActivity 為例,原始碼如下:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // ...其餘邏輯... } }
編譯之後的程式碼為(反編譯):
public class MainActivity extends AppCompatActivity { public void onCreate(Bundle paramBundle) { IncrementalChange localIncrementalChange = $change; if (localIncrementalChange != null) { localIncrementalChange.access$dispatch("onCreate.(Landroid/os/Bundle;)V", new Object[] { this, paramBundle }); return; } super.onCreate(paramBundle); setContentView(2130968601); // ...其餘邏輯... } }
可以看到,每個方法前都注入了這段邏輯。
當我們修改程式碼中方法的實作之後,點擊 Instant Run,它會生成對應的 patch 文件來記錄你修改的內容。patch 文件中的替換類是在所修改類名後面追加 $override,並實作 IncrementalChange 介面。以 MainActivity 為例,在目錄 ../build/intermediates/transforms/instantRun/debug/folders/4000/5 下可找到生成的 MainActivity$override 類。
public class MainActivity$override implements IncrementalChange { public static void onCreate(MainActivity $this, Bundle savedInstanceState) { // 修改後的方法實作 } public Object access$dispatch(String var1, Object... var2) { switch(var1.hashCode()) { case -641568046: onCreate((MainActivity)var2[0], (Bundle)var2[1]); return null; default: throw new InstantReloadException(...); } } }
生成 AppPatchesLoaderImpl 類別,繼承自 AbstractPatchesLoaderImpl,並實作 getPatchedClasses 方法,來記錄哪些類別被修改了。同樣在目錄 ../build/intermediates/transforms/instantRun/debug/folders/4000/5 下查找 AppPatchesLoaderImpl.class。
public class AppPatchesLoaderImpl extends AbstractPatchesLoaderImpl { public String[] getPatchedClasses() { return new String[]{"mobctrl.net.testinstantrun.MainActivity"}; } }
調用 load 方法之後,根據 getPatchedClasses 返回的修改過的類別列表,去加載對應的 $override 類別,然後把原有類別的 $change 設定為對應的實作了 IncrementalChange 介面的 $override 類別,然後等待 restart 之後生效。
private static int handleResourcePatch(int updateMode, ApplicationPatch patch, String path) { FileManager.writeAaptResources(path, patch.getBytes()); updateMode = Math.max(updateMode, 2); return updateMode; }
將資源的 patch 寫入到私有目錄,等到 restart 之後生效。
根據不同的 Instant Run updateMode 模式進行重啟,使上述三種部署模式生效:
private void restart(int updateMode, boolean incrementalResources, boolean toast) { if ((updateMode == 0) || (updateMode == 1)) { // 熱部署:無需重啟 Activity,直接套用增量程式碼 return; } List activities = Restarter.getActivities(this.mApplication, false); if ((incrementalResources) && (updateMode == 2)) { // 溫部署:更新資源文件 File file = FileManager.getExternalResourceFile(); if (file != null) { String resources = file.getPath(); MonkeyPatcher.monkeyPatchApplication(this.mApplication, null, null, resources); MonkeyPatcher.monkeyPatchExistingResources(this.mApplication, resources, activities); } } Activity activity = Restarter.getForegroundActivity(this.mApplication); if (updateMode == 2) { if (activity != null) { // 只重啟 Activity Restarter.restartActivityOnUiThread(activity); return; } updateMode = 3; } if (updateMode == 3) { // 冷部署:等待 app 被 IDE 殺死並重啟 } }
總結起來,Instant Run 主要做了以下幾件事:
1. 把 Instant-Run.jar 和 instant-Run-bootstrap.jar 打包到主 dex 中。
2. 替換 AndroidManifest.xml 中的 application 配置。
3. 使用 asm 工具,在每個類中添加 $change,在每個方法前加邏輯。
4. 把源碼編譯成 dex,然後存放到壓縮包 instant-run.zip 中。
1. 獲取更改後資源 resource.ap_ 的路徑。
2. 設置 ClassLoader:使用 IncrementalClassLoader 加載 apk 的程式碼,將原有的 BootClassLoader → PathClassLoader 改為 BootClassLoader → IncrementalClassLoader → PathClassLoader 的繼承關係。
3. createRealApplication:建立 apk 真實的 application。
4. monkeyPatchApplication:反射替換 ActivityThread 中的各種 Application 成員變量。
5. monkeyPatchExistingResource:反射替換所有存在的 AssetManager 物件。
6. 調用 realApplication 的 onCreate 方法。
7. 啟動 Server,透過 Socket 接收 patch 列表。
1. 生成對應的 $override 類別。
2. 生成 AppPatchesLoaderImpl 類別,記錄修改的類別列表。
3. 打包成 patch,透過 socket 傳遞給 app。
4. app 的 server 接收到 patch 之後,分別按照 handleColdSwapPatch、handleHotSwapPatch、handleResourcePatch 對 patch 進行處理。
5. restart 使 patch 生效。
Instant Run 的設計思路對以下幾個領域具有很好的參考價值:
<未完待續>
我自己透過 jd-gui 反編譯獲取的,可以參考:
https://github.com/nuptboyzhb/AndroidInstantRun
Android 記憶體洩漏的常見成因總結
Java 是一種具備垃圾回收機制的語言,它的優點在於開發者無需特別管理記憶體配置,既降低了應用因局部故障(segmentation fault)而崩潰的風險,也避免了未釋
Android 事件分發機制實例驗證:dispatchTouchEvent 與 onTouchEvent
前言 Android 的 Touch 事件分發機制是介面開發的基礎。當使用者點擊畫面時,事件會從 Activity 往下傳到 ViewGroup,再傳到 View;是否攔
手機怎麼掃二維碼?微信、QQ、手機百度三種方式圖解
掃碼已經是日常操作,但除了微信,其實還有幾個常用 App 都能勝任,而且各有各的順手之處。 一、用微信掃 打開微信,點擊右上角的「+」,從選單中選擇「掃一掃」。 把取景
DrySister 圖片應用實作:加入 SQLite 離線快取
為什麼需要資料快取 在 DrySister 的第一版中,我們已經加入非同步圖片載入與記憶體、磁碟快取。不過,若只在有網路時取得圖片資訊,一旦離線後重新進入 App,雖然圖