前言
? ? ? ? ? 繼上一篇Android 路由實踐(一)之后,斷更已經差不多一個月,畢竟是年前的最后一個月,各種事情扎堆,直到近幾天才稍微閑下來,于是有了此文。簡單回顧下,上一篇文章中簡單介紹了三種實現路由的方式,分別是:隱式的Intent、通過初始化路由表的方式實現、通過注解。最后總結了下優缺點,建議使用第二種,今天我們講下第四種,為啥單開一篇文章呢?因為第四種涉及到知識點有點多,并且參考ButterKbife以及部分阿里巴巴ARouter的實現。
大體思路
? ? ? ? ?通過 annotationProcessor處理編譯期注解,在編譯的時候給路由表注入數據,這樣在運行時通過annotationProcessor生成java代碼并編譯class文件。以下代碼部分參考了Butterknife的實現:
/*** 自定義的編譯期Processor,用于生成xxx$$Router.java文件*/
@AutoService(Processor.class)
public class RouterProcessor extends AbstractProcessor {/*** 文件相關的輔助類*/private Filer mFiler;/*** 元素相關的輔助類*/private Elements mElementUtils;/*** 日志相關的輔助類*/private Messager mMessager;/*** 解析的目標注解集合*/@Overridepublic synchronized void init(ProcessingEnvironment processingEnv) {super.init(processingEnv);mElementUtils = processingEnv.getElementUtils();mMessager = processingEnv.getMessager();mFiler = processingEnv.getFiler();}@Overridepublic Set<String> getSupportedAnnotationTypes() {Set<String> types = new LinkedHashSet<>();types.add(RouterTarget.class.getCanonicalName());return types;}@Overridepublic SourceVersion getSupportedSourceVersion() {return SourceVersion.latestSupported();}@Overridepublic boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {mMessager.printMessage(Diagnostic.Kind.WARNING, "processprocessprocessprocess");Set<? extends Element> routeElements = roundEnv.getElementsAnnotatedWith(RouterTarget.class);for (Element element : routeElements) {String packageName = element.getEnclosingElement().toString();String fullClassName = element.toString();String className = fullClassName.substring(fullClassName.indexOf(packageName) + packageName.length() + 1, fullClassName.length());/**// * 構建類// */try {RouterTarget annotation = element.getAnnotation(RouterTarget.class);RouterByAnnotationManager.getInstance().addRouter(annotation.value(), element.toString());mMessager.printMessage(Diagnostic.Kind.WARNING, RouterByAnnotationManager.getInstance().getRouter(annotation.value()) + RouterByAnnotationManager.getInstance());FieldSpec routerKey = FieldSpec.builder(String.class, "routerKey", Modifier.FINAL, Modifier.PRIVATE).initializer("$S", annotation.value()).build();FieldSpec clazz = FieldSpec.builder(String.class, "fullClassName", Modifier.FINAL, Modifier.PRIVATE).initializer("$S", fullClassName).build();/*** 構建方法*/MethodSpec methodSpec = MethodSpec.methodBuilder("injectRouter").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addCode("com.example.commonlib.RouterByAnnotationManager.getInstance().addRouter($L,$L);", "routerKey", "fullClassName").build();TypeSpec finderClass = TypeSpec.classBuilder(className + "$$Router").addModifiers(Modifier.PUBLIC).addMethod(methodSpec).addField(routerKey).addField(clazz).addSuperinterface(RouterInjector.class).build();JavaFile.builder(packageName, finderClass).build().writeTo(mFiler);} catch (Exception e) {error("processBindView", e.getMessage());}}return true;}public String getPackageName(TypeElement type) {return mElementUtils.getPackageOf(type).getQualifiedName().toString();}private void error(String msg, Object... args) {mMessager.printMessage(Diagnostic.Kind.ERROR, String.format(msg, args));}private void info(String msg, Object... args) {mMessager.printMessage(Diagnostic.Kind.NOTE, String.format(msg, args));}
}復制代碼
注意getSupportedAnnotationTypes(),如果你要對那些類進行處理,就要把Class的類名加入到Set中并且返回。然后看下process()方法,里面利用javaPoet生成java文件,文件形如UserInfoActivity$$Router,內容如下:
import java.lang.Override;
import java.lang.String;public class UserInfoActivity$$Router implements RouterInjector {private final String routerKey = "android.intent.action.USERINFO";private final String fullClassName = "com.example.userlib.UserInfoActivity";@Overridepublic void injectRouter() {com.example.commonlib.RouterByAnnotationManager.getInstance().addRouter(routerKey,fullClassName);}
}
復制代碼
那么相信重點來了,怎么去調用injectRouter()方法,將數據注入到路由表中,到這里的時候
差點因為這個問題前功盡棄,最后祭出了阿里大法,參考了ARouter的實現。具體如下:
通過Application對Router進行初始化:
public class RouterApplication extends Application {@Overridepublic void onCreate() {super.onCreate();//初始化路由Router.init(this);}
}復制代碼
Router初始化的時候通過反射將數據注入到路由表
public static void init(Application application) {try {Set<String> classNames = ClassUtils.getFileNameByPackageName(application, ActionConstant.SUFFIX);for (String className : classNames) {RouterFinder.bind(className);}} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}復制代碼
來看下阿里ARouter的反射幫助類:
**這個類是從alibaba的ARouter復制過來的用來掃描所有的類等*/
public class ClassUtils {private static final String EXTRACTED_NAME_EXT = ".classes";private static final String EXTRACTED_SUFFIX = ".zip";private static final String SECONDARY_FOLDER_NAME = "code_cache" + File.separator + "secondary-dexes";private static final String PREFS_FILE = "multidex.version";private static final String KEY_DEX_NUMBER = "dex.number";private static final int VM_WITH_MULTIDEX_VERSION_MAJOR = 2;private static final int VM_WITH_MULTIDEX_VERSION_MINOR = 1;private static SharedPreferences getMultiDexPreferences(Context context) {return context.getSharedPreferences(PREFS_FILE, Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? Context.MODE_PRIVATE : Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);}/*** 通過指定包名,掃描包下面包含的所有的ClassName** @param context U know* @param suffix 包名* @return 所有class的集合*/public static Set<String> getFileNameByPackageName(Context context, final String suffix) throws PackageManager.NameNotFoundException, IOException, InterruptedException {final Set<String> classNames = new HashSet<>();List<String> paths = getSourcePaths(context);final CountDownLatch parserCtl = new CountDownLatch(paths.size());for (final String path : paths) {RouterPoolExecutor.getInstance().execute(new Runnable() {@Overridepublic void run() {DexFile dexfile = null;try {if (path.endsWith(EXTRACTED_SUFFIX)) {//NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache"dexfile = DexFile.loadDex(path, path + ".tmp", 0);} else {dexfile = new DexFile(path);}Enumeration<String> dexEntries = dexfile.entries();while (dexEntries.hasMoreElements()) {String className = dexEntries.nextElement();if (className.endsWith(suffix)) {classNames.add(className);}}} catch (Throwable ignore) {Log.e("ARouter", "Scan map file in dex files made error.", ignore);} finally {if (null != dexfile) {try {dexfile.close();} catch (Throwable ignore) {}}parserCtl.countDown();}}});}parserCtl.await();Log.e("getFileNameByPackage", "Filter " + classNames.size() + " classes by packageName <" + suffix + ">");return classNames;}/*** get all the dex path** @param context the application context* @return all the dex path* @throws PackageManager.NameNotFoundException* @throws IOException*/public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException {ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);File sourceApk = new File(applicationInfo.sourceDir);List<String> sourcePaths = new ArrayList<>();sourcePaths.add(applicationInfo.sourceDir); //add the default apk path//the prefix of extracted file, ie: test.classesString extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;// 如果VM已經支持了MultiDex,就不要去Secondary Folder加載 Classesx.zip了,那里已經么有了
// 通過是否存在sp中的multidex.version是不準確的,因為從低版本升級上來的用戶,是包含這個sp配置的if (!isVMMultidexCapable()) {//the total dex numbersint totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {//for each dex file, ie: test.classes2.zip, test.classes3.zip...String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;File extractedFile = new File(dexDir, fileName);if (extractedFile.isFile()) {sourcePaths.add(extractedFile.getAbsolutePath());//we ignore the verify zip part} else {throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'");}}}sourcePaths.addAll(tryLoadInstantRunDexFile(applicationInfo));return sourcePaths;}/*** Get instant run dex path, used to catch the branch usingApkSplits=false.*/private static List<String> tryLoadInstantRunDexFile(ApplicationInfo applicationInfo) {List<String> instantRunSourcePaths = new ArrayList<>();if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && null != applicationInfo.splitSourceDirs) {// add the split apk, normally for InstantRun, and newest version.instantRunSourcePaths.addAll(Arrays.asList(applicationInfo.splitSourceDirs));Log.d("tryLoadInstantRunDex", "Found InstantRun support");} else {try {// This man is reflection from Google instant run sdk, he will tell me where the dex files go.Class pathsByInstantRun = Class.forName("com.android.tools.fd.runtime.Paths");Method getDexFileDirectory = pathsByInstantRun.getMethod("getDexFileDirectory", String.class);String instantRunDexPath = (String) getDexFileDirectory.invoke(null, applicationInfo.packageName);File instantRunFilePath = new File(instantRunDexPath);if (instantRunFilePath.exists() && instantRunFilePath.isDirectory()) {File[] dexFile = instantRunFilePath.listFiles();for (File file : dexFile) {if (null != file && file.exists() && file.isFile() && file.getName().endsWith(".dex")) {instantRunSourcePaths.add(file.getAbsolutePath());}}Log.d("tryLoadInstantRunDex", "Found InstantRun support");}} catch (Exception e) {Log.d("tryLoadInstantRunDex", "InstantRun support error, " + e.getMessage());}}return instantRunSourcePaths;}/*** Identifies if the current VM has a native support for multidex, meaning there is no need for* additional installation by this library.** @return true if the VM handles multidex*/private static boolean isVMMultidexCapable() {boolean isMultidexCapable = false;String vmName = null;try {if (isYunOS()) { // YunOS需要特殊判斷vmName = "'YunOS'";isMultidexCapable = Integer.valueOf(System.getProperty("ro.build.version.sdk")) >= 21;} else { // 非YunOS原生AndroidvmName = "'Android'";String versionString = System.getProperty("java.vm.version");if (versionString != null) {Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+)?").matcher(versionString);if (matcher.matches()) {try {int major = Integer.parseInt(matcher.group(1));int minor = Integer.parseInt(matcher.group(2));isMultidexCapable = (major > VM_WITH_MULTIDEX_VERSION_MAJOR)|| ((major == VM_WITH_MULTIDEX_VERSION_MAJOR)&& (minor >= VM_WITH_MULTIDEX_VERSION_MINOR));} catch (NumberFormatException ignore) {// let isMultidexCapable be false}}}}} catch (Exception ignore) {}Log.i("isVMMultidexCapable", "VM with name " + vmName + (isMultidexCapable ? " has multidex support" : " does not have multidex support"));return isMultidexCapable;}/*** 判斷系統是否為YunOS系統*/private static boolean isYunOS() {try {String version = System.getProperty("ro.yunos.version");String vmName = System.getProperty("java.vm.name");return (vmName != null && vmName.toLowerCase().contains("lemur"))|| (version != null && version.trim().length() > 0);} catch (Exception ignore) {return false;}}
}復制代碼
注意看tryLoadInstantRunDexFile()這個方法,記得在上一篇文章中說到資源路徑獲得DexFile,注意5.0以上版本要求關掉instant run 方法否則會自動拆包遍歷不到所有activity類,導致有些加了RouterTarget注解的Activity掃描不到,Arouter在tryLoadInstantRunDexFile()解決了這個問題,如果不調用這個方法的話,,只有如下圖的apk:
base.apk一般是不包括我們自己寫的代碼,這個方法調用之后結果如下:
可以掃描到所有的apk,之后接下來我們就可以解壓出項目里面所有的類,通過找出類名后綴為$$Router的類進行發射,代碼如下:
/*** 通過指定包名,掃描包下面包含的所有的ClassName** @param context U know* @param suffix 包名* @return 所有class的集合*/
public static Set<String> getFileNameByPackageName(Context context, final String suffix) throws PackageManager.NameNotFoundException, IOException, InterruptedException {final Set<String> classNames = new HashSet<>();List<String> paths = getSourcePaths(context);final CountDownLatch parserCtl = new CountDownLatch(paths.size());for (final String path : paths) {RouterPoolExecutor.getInstance().execute(new Runnable() {@Overridepublic void run() {DexFile dexfile = null;try {if (path.endsWith(EXTRACTED_SUFFIX)) {//NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache"dexfile = DexFile.loadDex(path, path + ".tmp", 0);} else {dexfile = new DexFile(path);}Enumeration<String> dexEntries = dexfile.entries();while (dexEntries.hasMoreElements()) {String className = dexEntries.nextElement();if (className.endsWith(suffix)) {classNames.add(className);}}} catch (Throwable ignore) {Log.e("ARouter", "Scan map file in dex files made error.", ignore);} finally {if (null != dexfile) {try {dexfile.close();} catch (Throwable ignore) {}}parserCtl.countDown();}}});}parserCtl.await();Log.e("getFileNameByPackage", "Filter " + classNames.size() + " classes by packageName <" + suffix + ">");return classNames;
}復制代碼
注意這里:
dexfile = new DexFile(path);復制代碼
我們上一篇文章中建議不要使用,因為安卓8.0已經打上了廢棄標志
但是既然阿里爸爸這么用了,相信以后也會有相應的解決辦法,我們及時跟進,如果讀者有好的方法,歡迎提出,大家一起研究研究,接下來就是反射調用injectRouter() ,
public class RouterFinder {public RouterFinder() {throw new AssertionError("No .instances");}private static Map<String, RouterInjector> FINDER_MAP = new HashMap<>();/*** 獲取目標類** @param className*/public static void inject(String className) {try {Log.e("inject",className);RouterInjector injector = FINDER_MAP.get(className);if (injector == null) {Class<?> finderClass = Class.forName(className);injector = (RouterInjector) finderClass.newInstance();FINDER_MAP.put(className, injector);}injector.injectRouter();} catch (Exception e) {}}}復制代碼
到此完成了路由表的數據填充,具體使用如下:
new Router.Builder(this, RouterByAnnotationManager.getInstance().getRouter(ActionConstant.ACTION_USER_INFO)).addParams(ActionConstant.KEY_USER_NAME, etUserName.getText().toString()).addParams(ActionConstant.KEY_PASS_WORD, etPassWord.getText().toString()).go();復制代碼
到此完成了編譯期路由的實現,牽扯的東西還是挺多,歷經千辛萬苦。代碼github,喜歡的給個星吧!