Android插件化不算是一門新技術,發展了有一些年頭了。不一樣公司的插件化方案大致原理上很類似。本文經過閱讀愛奇藝的Neptune
框架來介紹插件化的總體思路和流程。java
所謂的插件其實本質上也是一個apk。在原生的Android應用中,apk在運行時會被映射成一個LoadedApk
對象。插件在安裝以後也會被映射成相似的PluginLoadedApk
對象,統一管理插件的相關信息。android
public class PluginLoadedApk {
public static final ConcurrentMap<String, Vector<Method>> sMethods = new ConcurrentHashMap<String, Vector<Method>>(1);
private static final String TAG = "PluginLoadedApk";
/* 保存注入到宿主ClassLoader的插件 */
private static Set<String> sInjectedPlugins = Collections.synchronizedSet(new HashSet<String>());
/* 保存全部的插件ClassLoader */
private static Map<String, DexClassLoader> sAllPluginClassLoader = new ConcurrentHashMap<>();
/* 宿主的Context */
private final Context mHostContext;
/* 宿主的ClassLoader */
private final ClassLoader mHostClassLoader;
/* 宿主的Resource對象 */
private final Resources mHostResource;
/* 宿主的包名 */
private final String mHostPackageName;
/* 插件的路徑 */
private final String mPluginPath;
/* 插件運行的進程名 */
private final String mProcessName;
/* 插件ClassLoader的parent */
private ClassLoader mParent;
/* 插件的類加載器 */
private DexClassLoader mPluginClassLoader;
/* 插件的Resource對象 */
private Resources mPluginResource;
/* 插件的AssetManager對象 */
private AssetManager mPluginAssetManager;
/* 插件的全局默認主題 */
private Resources.Theme mPluginTheme;
/* 插件的詳細信息,主要經過解析AndroidManifest.xml得到 */
private PluginPackageInfo mPluginPackageInfo;
/* 插件工程的包名 */
private String mPluginPackageName;
/* 插件的Application */
private Application mPluginApplication;
/* 自定義插件Context,主要用來改寫其中的一些方法從而改變插件行爲 */
private PluginContextWrapper mPluginAppContext;
/* 自定義Instrumentation,對Activity跳轉進行攔截 */
private PluginInstrument mPluginInstrument;
...
}
複製代碼
插件的安裝分爲內置插件(asset目錄,sdcard)和線上插件兩部分。api
插件的安裝經過運行在獨立進程的Service完成,主要防止部分機型dexopt hang住主進程。數組
Android根據系統版本不一樣會採用兩種虛擬機。Dalvik虛擬機是JIT方式解釋執行dex字節碼;ART虛擬機是AOT方式將dex字節碼轉化爲oat機器碼。緩存
若是當前運行在Dalvik虛擬機下,Dalvik會對classes.dex進行一次「翻譯」,「翻譯」的過程也就是守護進程installd的函數dexopt來對dex字節碼進行優化,實際上也就是由dex文件生成odex文件,最終odex文件被保存在手機的VM緩存目錄data/dalvik-cache下(注意!這裏所生成的odex文件依舊是以dex爲後綴名,格式如:system@priv-app@Settings@Settings.apk@classes.dex)。若是當前運行於ART模式下, ART一樣會在首次進入系統的時候調用/system/bin/dexopt(此處應該是dex2oat工具吧)工具來將dex字節碼翻譯成本地機器碼,保存在data/dalvik-cache下。 那麼這裏須要注意的是,不管是對dex字節碼進行優化,仍是將dex字節碼翻譯成本地機器碼,最終獲得的結果都是保存在相同名稱的一個odex文件裏面的,可是前者對應的是一個.dex文件(表示這是一個優化過的dex),後者對應的是一個.oat文件。經過這種方式,原來任何經過絕對路徑引用了該odex文件的代碼就都不須要修改了。 因爲在系統首次啓動時會對應用進行安裝,那麼在預置APK比較多的狀況下,將會大大增長系統首次啓動的時間。app
對於插件安裝來講,插件的安裝經過運行在獨立進程的Service完成,主要防止部分機型dexopt hang住主進程。框架
插件安裝過程主要執行如下幾步:異步
Java中的類都是經過ClassLoader加載的,而Android中類的加載也離不開ClassLoadder。在Android系統中,主要的ClassLoader有三個:ide
某個特定的類加載器在接到加載類的請求時,首先將加載任務委託給父類加載器,依次遞歸,若是父類加載器能夠完成類加載任務,就成功返回;只有父類加載器沒法完成此加載任務時,才本身去加載。函數
關於插件中類的加載機制有兩種處理方式,一種是單類加載機制,另外一種是多類加載機制;單類加載器機制,即全部插件APP的類都經過宿主的ClassLoader(即PathClassLoader)進行加載,與MultiDex、Qzone熱修復技術相似,經過Dex前插後者後插的方式實現。採用單類加載器模型,隨着業務團隊和插件的增長,很容易出現類重複問題,沒法保證全部類都是獨一無二的。多類加載器機制是指每一個插件都由一個新的類加載器實例來加載,組件間的類是徹底隔離,不能直接互相訪問。
利用ClassLoader的雙親委派機制,多類加載有兩種思路:
PluginLoadedApk
維護一個PluginClassLoader
實例,其父ClassLoader是PathClassLoader;在類加載時,先嚐試從宿主的ClassLoader加載,再嘗試本插件的ClassLoader加載。(好處:每一個插件維護本身的PluginLoadedApk
,不存在分發,類隔離作的更好)Android APP運行除了類還有資源,運行時須要加載資源;對於Android來講,資源是經過AssetManager和Resources這兩個類管理。App在運行時查找資源是經過當前Context的Resource實例中查找,在Resource內部是經過AssetManager管理當前的資源,AssetManager維護了資源包路徑的數組。插件化的原理,就是將插件的資源路徑添加到AssetManager的資源路徑數組中,經過反射AssetManager的隱藏方法addAssetPath實現插件資源的加載。
try{
AssetManager am = AssetManager.class.newInstance();
Method addAssetPath = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
addAssetPath.setAccessible(true);
addAssetPath.invoke(am, pluginApkPath);
Resources pluginResources = new Resources(am, hostResource.getDisplayMetrics(), hostResources.getConfiguration());
} catch (Exception e) {
e.printStackTrace();
}
複製代碼
各類插件化方案的資源加載原理都是同樣,區別主要在於不一樣插件的資源管理,是公用一套資源仍是插件獨立資源,插件和宿主的資源訪問ID衝突問題。
限制:插件不能使用本身的轉場動畫,只能使用宿主、系統定義的轉場動畫。
轉場動畫最終會調用到IActivityManager
,發起IPC請求,與AMS交互
public void overridePendingTransition(IBinder token, String packageName, int enterAnim, int exitAnim) throws RemoteException;
複製代碼
先附上兩張Android原生打包流程圖

在插件編譯打包時,須要完成如下幾件事:
Activity啓動能夠分爲兩個階段:往AMS發起啓動Activity的請求、AMS校驗後執行Activity啓動。
在Android 8.0(api 26)如下,應用往AMS發起啓動Activity請求的流程如上。在Android 8.0及以上版本,AMN、AMP已經被棄用,而是使用ActivityManager
類;參考文章。
Android P(api 28)對Activity的啓動過程作了修改;在Android P以前,是在H類的handleMessage方法的switch分支語句中,有專門處理啓動Activity的邏輯
public void handleMessage(Message msg) {
switch (msg.what) {
case LAUNCH_ACTIVITY: {
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
} break;
//如下省略不少代碼
}
}
複製代碼
在Android P中,啓動Activity的這部分邏輯,被轉移到了LaunchActivityItem類的execute方法中
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) {
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}
}
複製代碼
Android P把H類中的100-109這10個消息都刪除了,取而代之的是159這個消息,名爲EXECUTE_TRANSACTION。收斂了Activity相關的message分發。
Service啓動能夠分爲兩個階段:往AMS發起啓動Service的請求、AMS校驗後執行Service啓動。
在Android 8.0(api 26)如下,應用往AMS發起啓動Service請求的流程如上。在Android 8.0及以上版本,AMN、AMP已經被棄用,而是使用ActivityManager類。
廣播分爲靜態廣播、動態廣播。動態廣播在運行時向AMS註冊相關信息。
Neptune
類是整個插件系統的入口類,主要方法以下
/** * 初始化Neptune插件環境 * * @param application 宿主的Appliction * @param config 配置信息 */
public static void init(Application application, NeptuneConfig config) {
sHostContext = application;
sGlobalConfig = config != null ? config
: new NeptuneConfig.NeptuneConfigBuilder().build();
PluginDebugLog.setIsDebug(sGlobalConfig.isDebug());
boolean hookInstr = VersionUtils.hasPie() || sGlobalConfig.getSdkMode() != NeptuneConfig.LEGACY_MODE;
if (hookInstr) {
//Hook Instrumentation
hookInstrumentation();
}
// 調用getInstance()方法會初始化bindService,管理插件安裝的Service
PluginPackageManagerNative.getInstance(sHostContext).setPackageInfoManager(sGlobalConfig.getPluginInfoProvider());
// 註冊插件卸載監聽廣播
PluginManager.registerUninstallReceiver(sHostContext);
}
複製代碼
/** * 啓動插件 * * @param mHostContext 主工程的上下文 * @param mIntent 須要啓動的組件的Intent * @param mServiceConnection bindService時須要的ServiceConnection,若是不是bindService的方式啓動組件,傳入Null * @param mProcessName 須要啓動的插件運行的進程名稱,插件方能夠在Application的android:process指定 * 若是沒有指定,則有插件中心分配 */
public static void launchPlugin(final Context mHostContext, final Intent mIntent, final ServiceConnection mServiceConnection, final String mProcessName) {
final String packageName = tryParsePkgName(mHostContext, mIntent);
if (TextUtils.isEmpty(packageName)) {
if (null != mHostContext) {
deliver(mHostContext, false, mHostContext.getPackageName(), ErrorType.ERROR_PLUGIN_LOAD_NO_PKGNAME_INTENT);
}
PluginDebugLog.runtimeLog(TAG, "enterProxy packageName is null return! packageName: " + packageName);
return;
}
// 處理不一樣進程跳轉
final String targetProcessName = TextUtils.isEmpty(mProcessName) ?
ProcessManager.chooseDefaultProcess(mHostContext, packageName) : mProcessName;
String currentProcess = FileUtils.getCurrentProcessName(mHostContext);
if (!TextUtils.equals(currentProcess, targetProcessName)) {
// 啓動進程和目標進程不一致,須要先啓動目標進程,初始化PluginLoadedApk
Intent transIntent = new Intent();
transIntent.setAction(IntentConstant.ACTION_START_PLUGIN);
//目標進程的Service中從新經過mIntent啓動插件
transIntent.putExtra(IntentConstant.EXTRA_START_INTENT_KEY, mIntent);
transIntent.putExtra(IntentConstant.EXTRA_TARGET_PROCESS, targetProcessName);
try {
String proxyServiceName = ComponentFinder.matchServiceProxyByFeature(targetProcessName);
transIntent.setClass(mHostContext, Class.forName(proxyServiceName));
mHostContext.startService(transIntent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return;
}
LinkedBlockingQueue<Intent> cacheIntents = PActivityStackSupervisor.getCachedIntent(packageName);
//該插件有其餘任務排隊中,mIntent添加到隊尾
if (cacheIntents != null && cacheIntents.size() > 0) {
cacheIntents.add(mIntent);
PluginDebugLog.runtimeLog(TAG, "LoadingMap is not empty, Cache current intent, intent: " + mIntent + ", packageName: " + packageName);
return;
}
boolean isLoadAndInit = isPluginLoadedAndInit(packageName);
if (!isLoadAndInit) {
if (null == cacheIntents) {
cacheIntents = new LinkedBlockingQueue<Intent>();
PActivityStackSupervisor.addCachedIntent(packageName, cacheIntents);
}
// 緩存這個intent,等待PluginLoadedApk加載到內存以後再啓動這個Intent
PluginDebugLog.runtimeLog(TAG, "Environment is initializing and loading, cache current intent first, intent: " + mIntent);
cacheIntents.add(mIntent);
} else {
PluginDebugLog.runtimeLog(TAG, "Environment is already ready, launch current intent directly: " + mIntent);
//能夠直接啓動組件
readyToStartSpecifyPlugin(mHostContext, mServiceConnection, mIntent, true);
return;
}
// 處理插件的依賴關係
final PluginLiteInfo info = PluginPackageManagerNative.getInstance(mHostContext.getApplicationContext())
.getPackageInfo(packageName);
//獲取插件的依賴關係
final List<String> mPluginRefs = PluginPackageManagerNative.getInstance(mHostContext)
.getPluginRefs(packageName);
if (info != null && mPluginRefs != null
&& mPluginRefs.size() > 0) {
PluginDebugLog.runtimeLog(TAG,
"start to check dependence installation size: " + mPluginRefs.size());
//依賴的總數量
final AtomicInteger count = new AtomicInteger(mPluginRefs.size());
for (String pkgName : mPluginRefs) {
PluginDebugLog.runtimeLog(TAG, "start to check installation pkgName: " + pkgName);
final PluginLiteInfo refInfo = PluginPackageManagerNative.getInstance(mHostContext.getApplicationContext())
.getPackageInfo(pkgName);
PluginPackageManagerNative.getInstance(mHostContext.getApplicationContext()).packageAction(refInfo,
new IInstallCallBack.Stub() {
@Override
public void onPackageInstalled(PluginLiteInfo packageInfo) {
//未ready的依賴數量
count.getAndDecrement();
PluginDebugLog.runtimeLog(TAG, "check installation success pkgName: " + refInfo.packageName);
if (count.get() == 0) {
PluginDebugLog.runtimeLog(TAG,
"start Check installation after check dependence packageName: "
+ packageName);
//真正加載插件
checkPkgInstallationAndLaunch(mHostContext, info, mServiceConnection, mIntent, targetProcessName);
}
}
@Override
public void onPackageInstallFail(PluginLiteInfo info, int failReason) throws RemoteException {
PluginDebugLog.runtimeLog(TAG,
"check installation failed pkgName: " + info.packageName + " failReason: " + failReason);
count.set(-1);
}
});
}
} else if (info != null) {
PluginDebugLog.runtimeLog(TAG, "start Check installation without dependence packageName: " + packageName);
//真正加載插件
checkPkgInstallationAndLaunch(mHostContext, info, mServiceConnection, mIntent, targetProcessName);
} else {
//異常case
PluginDebugLog.runtimeLog(TAG, "pluginLiteInfo is null packageName: " + packageName);
PActivityStackSupervisor.clearLoadingIntent(packageName);
if (PluginDebugLog.isDebug()) {
throw new IllegalStateException("pluginLiteInfo is null when launchPlugin " + packageName);
}
}
}
複製代碼
/** * 真正啓動一個組件 * * @param mHostContext 主工程Context * @param mLoadedApk 須要啓動的插件的PluginLoadedApk * @param mIntent 須要啓動組件的Intent * @param mConnection bindService時須要的ServiceConnection,若是不是bindService的方式啓動組件,傳入Null */
private static void doRealLaunch(Context mHostContext, PluginLoadedApk mLoadedApk, Intent mIntent, ServiceConnection mConnection) {
String targetClassName = "";
ComponentName mComponent = mIntent.getComponent();
if (mComponent != null) {
//顯式啓動
targetClassName = mComponent.getClassName();
PluginDebugLog.runtimeLog(TAG, "launchIntent_targetClassName:" + targetClassName);
if (TextUtils.isEmpty(targetClassName)) {
targetClassName = mLoadedApk.getPluginPackageInfo().getDefaultActivityName();
}
}
String pkgName = mLoadedApk.getPluginPackageName();
Class<?> targetClass = null;
if (!TextUtils.isEmpty(targetClassName)
&& !TextUtils.equals(targetClassName, IntentConstant.EXTRA_VALUE_LOADTARGET_STUB)) {
try {
//插件ClassLoader加載類
targetClass = mLoadedApk.getPluginClassLoader().loadClass(targetClassName);
} catch (Exception e) {
deliver(mHostContext, false,
pkgName, ErrorType.ERROR_PLUGIN_LOAD_COMP_CLASS);
PluginDebugLog.runtimeLog(TAG, "launchIntent loadClass failed for targetClassName: "
+ targetClassName);
executeNext(mLoadedApk, mConnection, mHostContext);
return;
}
}
String action = mIntent.getAction();
if (TextUtils.equals(action, IntentConstant.ACTION_PLUGIN_INIT)
|| TextUtils.equals(targetClassName, IntentConstant.EXTRA_VALUE_LOADTARGET_STUB)) {
PluginDebugLog.runtimeLog(TAG, "launchIntent load target stub!");
//通知插件初始化完畢
if (targetClass != null && BroadcastReceiver.class.isAssignableFrom(targetClass)) {
Intent newIntent = new Intent(mIntent);
newIntent.setComponent(null);
newIntent.putExtra(IntentConstant.EXTRA_TARGET_PACKAGE_KEY, pkgName);
newIntent.setPackage(mHostContext.getPackageName());
//經過廣播通知插件加載完成
mHostContext.sendBroadcast(newIntent);
}
// 表示後臺加載,不須要處理該Intent
executeNext(mLoadedApk, mConnection, mHostContext);
return;
}
mLoadedApk.changeLaunchingIntentStatus(true);
PluginDebugLog.runtimeLog(TAG, "launchIntent_targetClass: " + targetClass);
if (targetClass != null && Service.class.isAssignableFrom(targetClass)) {
//處理的是Service, 宿主啓動插件Service只能經過顯式啓動
ComponentFinder.switchToServiceProxy(mLoadedApk, mIntent, targetClassName);
if (mConnection == null) {
mHostContext.startService(mIntent);
} else {
mHostContext.bindService(mIntent, mConnection,
mIntent.getIntExtra(IntentConstant.BIND_SERVICE_FLAGS, Context.BIND_AUTO_CREATE));
}
} else {
//處理的是Activity
ComponentFinder.switchToActivityProxy(pkgName,
mIntent, -1, mHostContext);
PActivityStackSupervisor.addLoadingIntent(pkgName, mIntent);
Context lastActivity = null;
PActivityStackSupervisor mActivityStackSupervisor =
mLoadedApk.getActivityStackSupervisor();
lastActivity = mActivityStackSupervisor.getAvailableActivity();
if (mHostContext instanceof Activity) {
mHostContext.startActivity(mIntent);
} else if (lastActivity != null) {
// Clear the Intent.FLAG_ACTIVITY_NEW_TASK
int flag = mIntent.getFlags();
flag = flag ^ Intent.FLAG_ACTIVITY_NEW_TASK;
mIntent.setFlags(flag);
lastActivity.startActivity(mIntent);
} else {
// Add the Intent.FLAG_ACTIVITY_NEW_TASK
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mHostContext.startActivity(mIntent);
}
}
// 執行下一個Intent
executeNext(mLoadedApk, mConnection, mHostContext);
}
複製代碼
/** * 異步初始化插件,宿主靜默加載插件 * * @deprecated 不建議使用 */
@Deprecated
public static void initPluginAsync(final Context mHostContext, final String packageName, final String processName, final org.qiyi.pluginlibrary.listenter.IPluginStatusListener mListener) {
// 插件已經加載
if (PluginManager.isPluginLoadedAndInit(packageName)) {
if (mListener != null) {
mListener.onInitFinished(packageName);
}
return;
}
BroadcastReceiver recv = new BroadcastReceiver() {
public void onReceive(Context ctx, Intent intent) {
String curPkg = IntentUtils.getTargetPackage(intent);
if (IntentConstant.ACTION_PLUGIN_INIT.equals(intent.getAction()) && TextUtils.equals(packageName, curPkg)) {
PluginDebugLog.runtimeLog(TAG, "收到自定義的廣播org.qiyi.pluginapp.action.TARGET_LOADED");
//插件初始化結束
if (mListener != null) {
mListener.onInitFinished(packageName);
}
mHostContext.getApplicationContext().unregisterReceiver(this);
}
}
};
PluginDebugLog.runtimeLog(TAG, "註冊自定義廣播org.qiyi.pluginapp.action.TARGET_LOADED");
IntentFilter filter = new IntentFilter();
filter.addAction(IntentConstant.ACTION_PLUGIN_INIT);
//註冊廣播
mHostContext.getApplicationContext().registerReceiver(recv, filter);
Intent intent = new Intent();
intent.setAction(IntentConstant.ACTION_PLUGIN_INIT);
intent.setComponent(new ComponentName(packageName, recv.getClass().getName()));
//發送一個啓動插件的intent
launchPlugin(mHostContext, intent, processName);
}
複製代碼
Hook系統原生的Instrument,替換成NeptuneInstrument。NeptuneInstrument
繼承PluginInstrument
。 PluginInstrument
負責往AMS發送的請求,NeptuneInstrument
負責AMS返回的結果處理。
/** * 負責轉移插件的跳轉目標<br> * 用於Hook插件Activity中Instrumentation * * @see android.app.Activity#startActivity(android.content.Intent) */
public class PluginInstrument extends Instrumentation {
private static final String TAG = "PluginInstrument";
private static ConcurrentMap<String, Vector<Method>> sMethods = new ConcurrentHashMap<String, Vector<Method>>(5);
Instrumentation mHostInstr;
private String mPkgName;
private ReflectionUtils mInstrumentRef;
/** * 插件的Instrumentation */
public PluginInstrument(Instrumentation hostInstr) {
this(hostInstr, "");
}
public PluginInstrument(Instrumentation hostInstr, String pkgName) {
mHostInstr = hostInstr;
mInstrumentRef = ReflectionUtils.on(hostInstr);
mPkgName = pkgName;
}
/** * 若是是PluginInstrumentation,拆裝出原始的HostInstr * * @param instrumentation * @return */
public static Instrumentation unwrap(Instrumentation instrumentation) {
if (instrumentation instanceof PluginInstrument) {
return ((PluginInstrument) instrumentation).mHostInstr;
}
return instrumentation;
}
/** * @Override */
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) {
...
}
/** * @Override */
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode) {
...
}
/** * @Override For below android 6.0 */
public ActivityResult execStartActivityAsCaller( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options, int userId) {
...
}
/** * @Override For android 6.0 */
public ActivityResult execStartActivityAsCaller( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options, boolean ignoreTargetSecurity, int userId) {
...
}
/** * @Override */
public void execStartActivitiesAsUser( Context who, IBinder contextThread, IBinder token, Activity target, Intent[] intents, Bundle options, int userId) {
...
}
/** * @Override For below android 6.0, start activity from Fragment */
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Fragment target, Intent intent, int requestCode, Bundle options) {
...
}
/** * @Override For android 6.0, start activity from Fragment */
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, String target, Intent intent, int requestCode, Bundle options) {
...
}
}
複製代碼
/** * 自定義的全局的Instrumentation * 負責轉移插件的跳轉目標和建立插件的Activity實例 * 用於Hook ActivityThread中的全局Instrumentation */
public class NeptuneInstrument extends PluginInstrument {
private static final String TAG = "NeptuneInstrument";
private PluginActivityRecoveryHelper mRecoveryHelper = new PluginActivityRecoveryHelper();
public NeptuneInstrument(Instrumentation hostInstr) {
super(hostInstr);
}
@Override
public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
...
}
@Override
public void callActivityOnCreate(Activity activity, Bundle icicle) {
...
}
@Override
public void callActivityOnDestroy(Activity activity) {
...
}
@Override
public void callActivityOnRestoreInstanceState(Activity activity, Bundle savedInstanceState) {
...
}
/** * 將Activity反射相關操做分發給插件Activity的基類 */
private boolean dispatchToBaseActivity(Activity activity) {
//這個模式已棄用
return Neptune.getConfig().getSdkMode() == NeptuneConfig.INSTRUMENTATION_BASEACT_MODE
&& activity instanceof IPluginBase;
}
}
複製代碼
NeptuneInstrument
類中的幾個方法有一些特殊的邏輯處理,下面單獨分析:
@Override
public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
if (className.startsWith(ComponentFinder.DEFAULT_ACTIVITY_PROXY_PREFIX)) {
// 插件代理Activity,替換回插件真實的Activity
String[] result = IntentUtils.parsePkgAndClsFromIntent(intent);
String packageName = result[0];
String targetClass = result[1];
PluginDebugLog.runtimeLog(TAG, "newActivity: " + className + ", targetClass: " + targetClass);
if (!TextUtils.isEmpty(packageName)) {
//找到對應插件
PluginLoadedApk loadedApk = PluginManager.getPluginLoadedApkByPkgName(packageName);
if (loadedApk != null && targetClass != null) {
Activity activity = mHostInstr.newActivity(loadedApk.getPluginClassLoader(), targetClass, intent);
activity.setIntent(intent);
if (!dispatchToBaseActivity(activity)) {
// 這裏須要替換Resources,是由於ContextThemeWrapper會緩存一個Resource對象,而在Activity#attach()和
// Activity#onCreate()之間,系統會調用Activity#setTheme()初始化主題,Android 4.1+
//替換成插件的Resource資源
ReflectionUtils.on(activity).setNoException("mResources", loadedApk.getPluginResource());
}
return activity;
} else if (loadedApk == null) {
// loadedApk 爲空,多是正在恢復進程,跳轉到 RecoveryActivity
return mHostInstr.newActivity(cl, mRecoveryHelper.selectRecoveryActivity(className), intent);
}
}
}
return mHostInstr.newActivity(cl, className, intent);
}
複製代碼
@Override
public void callActivityOnCreate(Activity activity, Bundle icicle) {
boolean isRecovery = activity instanceof TransRecoveryActivity0;
if (isRecovery) {
//插件加載中的Activity,使用宿主的Instrument
mRecoveryHelper.saveIcicle(activity, icicle);
mHostInstr.callActivityOnCreate(activity, null);
return;
}
final Intent intent = activity.getIntent();
String[] result = IntentUtils.parsePkgAndClsFromIntent(intent);
boolean isLaunchPlugin = false;
if (IntentUtils.isIntentForPlugin(intent)) {
String packageName = result[0];
String targetClass = result[1];
if (!TextUtils.isEmpty(packageName)) {
PluginDebugLog.runtimeLog(TAG, "callActivityOnCreate: " + packageName);
PluginLoadedApk loadedApk = PluginManager.getPluginLoadedApkByPkgName(packageName);
if (loadedApk != null) {
icicle = mRecoveryHelper.recoveryIcicle(activity, icicle);
// 設置 extra 的 ClassLoader,否則可能會出現 BadParcelException, ClassNotFound
if (icicle != null) {
icicle.setClassLoader(loadedApk.getPluginClassLoader());
}
if (!dispatchToBaseActivity(activity)) {
// 若是分發給插件Activity的基類了,就不須要在這裏反射hook替換相關成員變量了
try {
ReflectionUtils activityRef = ReflectionUtils.on(activity);
//設置爲插件資源
activityRef.setNoException("mResources", loadedApk.getPluginResource());
//設置插件的Application
activityRef.setNoException("mApplication", loadedApk.getPluginApplication());
Context pluginContext = new PluginContextWrapper(activity.getBaseContext(), packageName);
//替換爲PluginContextWrapper,處理inflate相關
ReflectionUtils.on(activity, ContextWrapper.class).set("mBase", pluginContext);
// 5.0如下ContextThemeWrapper內會保存一個mBase,也須要反射替換掉
ReflectionUtils.on(activity, ContextThemeWrapper.class).setNoException("mBase", pluginContext);
//替換爲插件的Instrumentation
ReflectionUtils.on(activity).setNoException("mInstrumentation", loadedApk.getPluginInstrument());
// 修改插件Activity的ActivityInfo, theme, window等信息
PluginActivityControl.changeActivityInfo(activity, targetClass, loadedApk);
} catch (Exception e) {
PluginDebugLog.runtimeLog(TAG, "callActivityOnCreate with exception: " + e.getMessage());
}
}
if (activity.getParent() == null) {
//Activity棧的邏輯是怎麼處理的?
loadedApk.getActivityStackSupervisor().pushActivityToStack(activity);
}
isLaunchPlugin = true;
}
}
IntentUtils.resetAction(intent); //恢復Action
}
try {
mHostInstr.callActivityOnCreate(activity, icicle);
if (isLaunchPlugin) {
NotifyCenter.notifyPluginStarted(activity, intent);
NotifyCenter.notifyPluginActivityLoaded(activity);
}
//check是否須要hook callActivityOnRestoreInstanceState方法
mRecoveryHelper.mockActivityOnRestoreInstanceStateIfNeed(this, activity);
} catch (Exception e) {
ErrorUtil.throwErrorIfNeed(e);
if (isLaunchPlugin) {
NotifyCenter.notifyStartPluginError(activity);
}
activity.finish();
}
}
複製代碼
@Override
public void callActivityOnDestroy(Activity activity) {
mHostInstr.callActivityOnDestroy(activity);
if (activity.getParent() != null) {
return;
}
final Intent intent = activity.getIntent();
String pkgName = IntentUtils.parsePkgNameFromActivity(activity);
if (IntentUtils.isIntentForPlugin(intent)
|| intent == null) {
// intent爲null時,若是可以從Activity中解析出pkgName,也應該是插件的頁面
if (!TextUtils.isEmpty(pkgName)) {
PluginDebugLog.runtimeLog(TAG, "callActivityOnDestroy: " + pkgName);
PluginLoadedApk loadedApk = PluginManager.getPluginLoadedApkByPkgName(pkgName);
if (loadedApk != null) {
//退出插件的Activity棧
loadedApk.getActivityStackSupervisor().popActivityFromStack(activity);
}
}
}
}
複製代碼
@Override
public void callActivityOnRestoreInstanceState(Activity activity, Bundle savedInstanceState) {
if (activity instanceof TransRecoveryActivity0) {
mRecoveryHelper.saveSavedInstanceState(activity, savedInstanceState);
return;
}
if (IntentUtils.isIntentForPlugin(activity.getIntent())) {
String pkgName = IntentUtils.parsePkgAndClsFromIntent(activity.getIntent())[0];
PluginLoadedApk loadedApk = PluginManager.getPluginLoadedApkByPkgName(pkgName);
if (loadedApk != null && savedInstanceState != null) {
//用插件的ClassLoader恢復數據
savedInstanceState.setClassLoader(loadedApk.getPluginClassLoader());
}
}
mHostInstr.callActivityOnRestoreInstanceState(activity, savedInstanceState);
}
複製代碼
/** * 插件的Activity棧抽象, 和系統的{@link com.android.server.am.ActivityStack}相似 */
public class PActivityStack {
private final LinkedList<Activity> mActivities;
// taskAffinity
private String taskName;
PActivityStack(String taskName) {
this.taskName = taskName;
mActivities = new LinkedList<>();
}
/** * 獲取當前任務棧的名稱 */
public String getTaskName() {
return taskName;
}
public LinkedList<Activity> getActivities() {
return mActivities;
}
public int size() {
return mActivities.size();
}
public synchronized boolean isEmpty() {
return mActivities.isEmpty();
}
// 放入鏈表的前面
public synchronized void push(Activity activity) {
mActivities.addFirst(activity);
}
public synchronized void insertFirst(Activity activity) {
mActivities.addLast(activity);
}
public synchronized boolean pop(Activity activity) {
return mActivities.remove(activity);
}
public synchronized Activity getTop() {
return mActivities.getFirst();
}
/** * 清空當前任務棧裏的Activity */
public void clear(boolean needFinish) {
Iterator<Activity> iterator = mActivities.iterator();
while (iterator.hasNext()) {
Activity activity = iterator.next();
if (activity != null && needFinish
&& !FileUtils.isFinished(activity)) {
activity.finish();
}
iterator.remove();
}
}
}
複製代碼
PActivityStackSupervisor
管理Activity任務棧
/** * 處理Activity的launchMode,給Intent添加相關的Flags */
public void dealLaunchMode(Intent intent) {
if (null == intent) {
return;
}
String targetActivity = IntentUtils.getTargetClass(intent);
if (TextUtils.isEmpty(targetActivity)) {
return;
}
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode target activity: " + intent + " source: "
+ targetActivity);
// 不支持LAUNCH_SINGLE_INSTANCE
ActivityInfo info = mLoadedApk.getPluginPackageInfo().getActivityInfo(targetActivity);
if (info == null || info.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
return;
}
boolean isSingleTop = info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
|| (intent.getFlags() & Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0;
boolean isSingleTask = info.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK;
boolean isClearTop = (intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0;
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode isSingleTop " + isSingleTop + " isSingleTask "
+ isSingleTask + " isClearTop " + isClearTop);
int flag = intent.getFlags();
PluginDebugLog.runtimeLog(TAG, "before flag: " + Integer.toHexString(intent.getFlags()));
if ((isSingleTop || isSingleTask) && (flag & Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0) {
flag = flag ^ Intent.FLAG_ACTIVITY_SINGLE_TOP;
}
if ((isSingleTask || isClearTop) && (flag & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
flag = flag ^ Intent.FLAG_ACTIVITY_CLEAR_TOP;
}
intent.setFlags(flag);
PluginDebugLog.runtimeLog(TAG, "after flag: " + Integer.toHexString(intent.getFlags()));
if (isSingleTop && !isClearTop) {
// 判斷棧頂是否爲須要啓動的Activity, 只須要處理前臺棧
Activity activity = null;
if (!mFocusedStack.isEmpty()) {
activity = mFocusedStack.getTop();
}
boolean hasSameActivity = false;
String proxyClsName = ComponentFinder.findActivityProxy(mLoadedApk, info);
if (activity != null) {
// 棧內有實例, 多是ProxyActivity,也多是插件真實的Activity
//Fix: 新的實現中只有插件真實的Activity
if (TextUtils.equals(proxyClsName, activity.getClass().getName())
|| TextUtils.equals(targetActivity, activity.getClass().getName())) {
String key = getActivityStackKey(activity);
if (!TextUtils.isEmpty(key) && TextUtils.equals(targetActivity, key)) {
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
hasSameActivity = true;
}
}
}
if (hasSameActivity) {
handleOtherPluginActivityStack(activity, mFocusedStack);
}
} else if (isSingleTask || isClearTop) {
PActivityStack targetStack; // 須要搜索的任務棧
boolean fromBackStack = false;
if (isClearTop) {
targetStack = mFocusedStack;
} else {
// singleTask
if (mLastFocusedStack != null
&& TextUtils.equals(mLastFocusedStack.getTaskName(), matchTaskName(info.taskAffinity))) {
// 後臺棧和Activity的taskAffinity匹配
targetStack = mLastFocusedStack;
fromBackStack = true;
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode search in background stack: " + info.taskAffinity);
} else {
// 前臺棧中搜索
targetStack = mFocusedStack;
}
}
// 查找棧中是否存在已有實例
Activity found = null;
// 遍歷已經起過的activity
for (Activity activity : targetStack.getActivities()) {
String proxyClsName = ComponentFinder.findActivityProxy(mLoadedApk, info);
if (activity != null) {
if (TextUtils.equals(proxyClsName, activity.getClass().getName())
|| TextUtils.equals(targetActivity, activity.getClass().getName())) {
String key = getActivityStackKey(activity);
if (!TextUtils.isEmpty(key) && TextUtils.equals(targetActivity, key)) {
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode found:" + IntentUtils.dump(activity));
found = activity;
break;
}
}
}
}
// 棧中已經有當前activity
if (found != null) {
// 處理其餘插件的邏輯
// 在以這兩種SingleTask, ClearTop flag啓動狀況下,在同一個棧的狀況下
handleOtherPluginActivityStack(found, targetStack);
// 處理當前插件的Activity
List<Activity> popActivities = new ArrayList<Activity>(5);
for (Activity activity : targetStack.getActivities()) {
if (activity == found) {
if (isSingleTask || isSingleTop) {
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode add single top flag!");
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
}
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode add clear top flag!");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
break;
}
popActivities.add(activity);
}
for (Activity act : popActivities) {
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode popActivities finish " + IntentUtils.dump(act));
popActivityFromStack(act);
if (!FileUtils.isFinished(act)) {
act.finish();
}
}
// 若是Activity是在後臺堆棧中找到的,須要合併先後臺棧
if (fromBackStack) {
// https://developer.android.com/guide/components/activities/tasks-and-back-stack
// 把返回棧中的Activity所有推到前臺
PActivityStack sysForeStack = findAssociatedStack(mFocusedStack);
PActivityStack sysBackStack = findAssociatedStack(mLastFocusedStack);
mergeActivityStack(sysBackStack, sysForeStack);
// 處理插件自身的棧
mergeActivityStack(mLastFocusedStack, mFocusedStack);
// 切換先後臺堆棧
switchToBackStack(mFocusedStack, mLastFocusedStack);
}
mLoadedApk.quitApp(false);
} else {
// 堆棧裏沒有找到,遍歷還未啓動cache中的activity記錄
LinkedBlockingQueue<Intent> records = sIntentCacheMap
.get(mLoadedApk.getPluginPackageName());
if (null != records) {
Iterator<Intent> recordIterator = records.iterator();
String notLaunchTargetClassName = null;
while (recordIterator.hasNext()) {
Intent record = recordIterator.next();
if (null != record) {
if (null != record.getComponent()) {
notLaunchTargetClassName = record.getComponent().getClassName();
}
if (TextUtils.equals(notLaunchTargetClassName, targetActivity)) {
PluginDebugLog.runtimeLog(TAG, "sIntentCacheMap found: " + targetActivity);
if (isSingleTask || isSingleTop) {
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
break;
}
}
}
}
// 遍歷啓動過程當中的activity記錄
List<Intent> loadingIntents = sIntentLoadingMap.get(mLoadedApk.getPluginPackageName());
if (null != loadingIntents) {
Iterator<Intent> loadingRecordIterator = loadingIntents.iterator();
String notLaunchTargetClassName = null;
while (loadingRecordIterator.hasNext()) {
Intent record = loadingRecordIterator.next();
if (null != record) {
notLaunchTargetClassName = IntentUtils.getTargetClass(record);
if (TextUtils.equals(notLaunchTargetClassName, targetActivity)) {
PluginDebugLog.runtimeLog(TAG,
"sIntentLoadingMap found: " + targetActivity);
if (isSingleTask || isSingleTop) {
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
break;
}
}
}
}
if (isSingleTask) {
// 是否須要放到單獨的任務棧
String taskName = matchTaskName(info.taskAffinity);
if (!TextUtils.equals(mFocusedStack.getTaskName(), taskName)) {
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode push activity into separated stack: " + taskName);
PActivityStack stack = mActivityStacks.get(taskName);
if (stack == null) {
// 建立一個新的任務棧
stack = new PActivityStack(taskName);
mActivityStacks.put(taskName, stack);
}
// 切換先後臺棧
switchToBackStack(mFocusedStack, stack);
} else {
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode push activity into current stack: " + taskName);
}
}
}
}
PluginDebugLog.runtimeLog(TAG, "dealLaunchMode end: " + intent + " "
+ targetActivity);
}
複製代碼
/** * 動態註冊插件中的靜態Receiver */
private void installStaticReceiver() {
if (mPluginPackageInfo == null || mHostContext == null) {
return;
}
Map<String, PluginPackageInfo.ReceiverIntentInfo> mReceiverIntentInfos =
mPluginPackageInfo.getReceiverIntentInfos();
if (mReceiverIntentInfos != null) {
Set<Map.Entry<String, PluginPackageInfo.ReceiverIntentInfo>> mEntrys =
mReceiverIntentInfos.entrySet();
Context mGlobalContext = mHostContext.getApplicationContext();
for (Map.Entry<String, PluginPackageInfo.ReceiverIntentInfo> mEntry : mEntrys) {
PluginPackageInfo.ReceiverIntentInfo mReceiverInfo = mEntry.getValue();
if (mReceiverInfo != null) {
try {
BroadcastReceiver mReceiver =
BroadcastReceiver.class.cast(mPluginClassLoader.
loadClass(mReceiverInfo.mInfo.name).newInstance());
List<IntentFilter> mFilters = mReceiverInfo.mFilter;
if (mFilters != null) {
for (IntentFilter mItem : mFilters) {
mGlobalContext.registerReceiver(mReceiver, mItem);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
複製代碼
PluginContextWrapper
類中完成了startService等方法的代理
@Override
public ComponentName startService(Intent service) {
PluginDebugLog.log(TAG, "startService: " + service);
PluginLoadedApk mLoadedApk = getPluginLoadedApk();
if (mLoadedApk != null) {
ComponentFinder.switchToServiceProxy(mLoadedApk, service);
}
return super.startService(service);
}
@Override
public boolean stopService(Intent name) {
PluginDebugLog.log(TAG, "stopService: " + name);
PluginLoadedApk mLoadedApk = getPluginLoadedApk();
if (mLoadedApk != null) {
String actServiceClsName = "";
if (name.getComponent() != null) {
actServiceClsName = name.getComponent().getClassName();
} else {
ServiceInfo mServiceInfo = getPluginPackageInfo().resolveService(name);
if (mServiceInfo != null) {
actServiceClsName = mServiceInfo.name;
}
}
PluginServiceWrapper plugin = PServiceSupervisor
.getServiceByIdentifer(PluginServiceWrapper.getIdentify(getPluginPackageName(), actServiceClsName));
if (plugin != null) {
plugin.updateServiceState(PluginServiceWrapper.PLUGIN_SERVICE_STOPED);
plugin.tryToDestroyService();
return true;
}
}
return super.stopService(name);
}
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
PluginDebugLog.log(TAG, "bindService: " + service);
PluginLoadedApk mLoadedApk = getPluginLoadedApk();
if (mLoadedApk != null) {
ComponentFinder.switchToServiceProxy(mLoadedApk, service);
}
if (conn != null) {
if (mLoadedApk != null && service != null) {
String serviceClass = IntentUtils.getTargetClass(service);
String packageName = mLoadedApk.getPluginPackageName();
if (!TextUtils.isEmpty(serviceClass) && !TextUtils.isEmpty(packageName)) {
PServiceSupervisor.addServiceConnectionByIdentifer(packageName + "." + serviceClass, conn);
}
}
}
return super.bindService(service, conn, flags);
}
@Override
public void unbindService(ServiceConnection conn) {
super.unbindService(conn);
PServiceSupervisor.removeServiceConnection(conn);
PluginDebugLog.log(TAG, "unbindService: " + conn);
}
複製代碼
Neptune
框架註釋比較清晰。可是因爲Neptune
框架代碼存在兩套對Activity插件化的方案實現(版本迭代,一套老的,一套新的),】,致使代碼邏輯不是很統一。在閱讀代碼的時候,把握住Hook思路,只看相關的代碼,仍是比較容易理解的。