前言
在使用smal重構(gòu)項(xiàng)目時(shí),碰到最大的問題就是業(yè)務(wù)插件布局id不能和公共庫(kù)的id重復(fù)。如果發(fā)生重復(fù)就會(huì)報(bào)java.lang.NoSuchFieldError: com.xxx.xxx.R$id.xxx,這個(gè)對(duì)項(xiàng)目插件化重構(gòu)的影響太大了,因?yàn)檫@個(gè)太難預(yù)測(cè)了,你無(wú)法知道id重復(fù)有哪些,只有一個(gè)個(gè)調(diào)試,發(fā)生錯(cuò)誤然后重新改id(在重構(gòu)前期就是這么干的/(ㄒoㄒ)/~~)。因此,必須得將這個(gè)問題解決。
解決思路
既然是報(bào)NoSuchFieldError,那應(yīng)該是插件中的R文件沒有這個(gè)id,使用Android Studio的Analyze Apk打開對(duì)應(yīng)的插件(將so重命名為apk),打開class.dex文件,找到對(duì)應(yīng)的R文件,發(fā)現(xiàn)確實(shí)是沒有那個(gè)id。在buildBundle的過程中,有一行日志比較重要
[app.news] split library R.java files... [ OK ]
正如它的表述的意思,拆分R文件成功。因此在生成R文件的過程中,他會(huì)將R文件拆分過濾,減少無(wú)用的id。我們將Small的編譯插件buildSrc引入到項(xiàng)目中,全局搜索“split library R.java files...”,找到了相關(guān)的代碼AppPlugin.groovy。
if (small.retainedTypes != null && small.retainedTypes.size() > 0) {
...
// Overwrite the aapt-generated R.java with full edition
aapt.generateRJava(small.rJavaFile, pkg, small.allTypes, small.allStyleables)
// Also generate a split edition for later re-compiling
aapt.generateRJava(small.splitRJavaFile, pkg,
small.retainedTypes, small.retainedStyleables)
...
Log.success "[${project.name}] split library R.java files..."
} else {
...
}
這里生成了兩個(gè)R文件,一個(gè)是包含所有資源的R文件,一個(gè)經(jīng)過過濾的R文件。
而第二個(gè)R文件會(huì)最終打包放入插件中。通過斷點(diǎn)調(diào)試插件,我們可以找到一些關(guān)鍵信息。

生成R文件需要4個(gè)參數(shù),我們重點(diǎn)關(guān)注第三個(gè)參數(shù)types。第一個(gè)R文件傳的是small.allTypes,而另外一個(gè)則是smal.retainedTypes(retained:保留;保持;)。這里我們可以通過打印的形式打印出來。發(fā)現(xiàn)retainedTypes就只保存了不重復(fù)的id。因此,只要我們?cè)谏傻诙€(gè)R文件中把重復(fù)的id加入進(jìn)去即可。
找到重復(fù)id
我們需要從allTypes中獲取重復(fù)id,合并retainedTypes生成一個(gè)新的retainedTypes1(為了不干擾,新建一個(gè)字段)。在此之前,需要知道retainedType和allTypes是怎么初始化的。通過搜索關(guān)鍵字,調(diào)試代碼。找到了關(guān)鍵代碼
protected void prepareSplit() {
...
def libEntries = [:]
def hostEntries = [:]
File hostSymbol = new File(rootSmall.preIdsDir, "${rootSmall.hostModuleName}-R.txt")
if (hostSymbol.exists()) {
libEntries += SymbolParser.getResourceEntries(hostSymbol)
hostEntries += SymbolParser.getResourceEntries(hostSymbol)
}
mTransitiveDependentLibProjects.each {
File libSymbol = new File(it.projectDir, 'public.txt')
libEntries += SymbolParser.getResourceEntries(libSymbol)
}
def publicEntries = SymbolParser.getResourceEntries(small.publicSymbolFile)
def bundleEntries = SymbolParser.getResourceEntries(idsFile)
def staticIdMaps = [:]
def staticIdStrMaps = [:]
def retainedEntries = []
def retainedPublicEntries = []
def retainedStyleables = []
def reservedKeys = getReservedResourceKeys()
bundleEntries.each { k, Map be ->
be._typeId = UNSET_TYPEID // for sort
be._entryId = UNSET_ENTRYID
Map le = publicEntries.get(k)
if (le != null) {
// Use last built id
be._typeId = le.typeId
be._entryId = le.entryId
retainedPublicEntries.add(be)
publicEntries.remove(k)
return
}
if (reservedKeys.contains(k)) {
be.isStyleable ? retainedStyleables.add(be) : retainedEntries.add(be)
return
}
le = libEntries.get(k)
if (le != null) {
// Add static id maps to host or library resources and map it later at
// compile-time with the aapt-generated `resources.arsc' and `R.java' file
staticIdMaps.put(be.id, le.id)
staticIdStrMaps.put(be.idStr, le.idStr)
return
}
...
be.isStyleable ? retainedStyleables.add(be) :retainedEntries.add(be)
}
...
retainedEntries.each { e ->
// Prepare entry id maps for resolving resources.arsc and binary xml files
if (currType == null || currType.name != e.type) {
// New type
currType = [type: e.vtype, name: e.type, id: e.typeId, _id: e._typeId, entries: []]
retainedTypes.add(currType)
}
...
def entry = [name: e.key, id: e.entryId, _id: e._entryId, v: e.id, _v: newResId,
vs : e.idStr, _vs: newResIdStr]
currType.entries.add(entry)
}
// Update the id array for styleables
retainedStyleables.findAll { it.mapped != null }.each {
it.idStr = "{ ${it.idStrs.join(', ')} }"
it.idStrs = null
}
// Collect all the resources for generating a temporary full edition R.java
// which required in javac.
// TODO: Do this only for the modules who's code really use R.xx of lib.*
def allTypes = []
def allStyleables = []
def addedTypes = [:]
libEntries.each { k, e ->
if (reservedKeys.contains(k)) return
if (e.isStyleable) {
allStyleables.add(e);
} else {
if (!addedTypes.containsKey(e.type)) {
// New type
currType = [type: e.vtype, name: e.type, entries: []]
allTypes.add(currType)
addedTypes.put(e.type, currType)
} else {
currType = addedTypes[e.type]
}
def entry = [name: e.key, _vs: e.idStr]
currType.entries.add(entry)
}
}
retainedTypes.each { t ->
def at = addedTypes[t.name]
if (at != null) {
at.entries.addAll(t.entries)
} else {
allTypes.add(t)
}
}
...
small.retainedTypes = retainedTypes
...
small.allTypes = allTypes
}
代碼比較多,prepareSplit方法大概400多行,不過通過調(diào)試還是能理清楚的。rentainedTypes是通過retainedEntries添加的,而retainedEntries則是在bundleEntries加入的。我們將以下代碼
be.isStyleable ? retainedStyleables.add(be) :retainedEntries.add(be)
改成
if (be.isStyleable) {
retainedStyleables.add(be)
} else {
retainedEntries.add(be)
retainedEntries1.add(be)
}
之前的libEntries.get()中加入重復(fù)id
le = libEntries.get(k)
if (le != null) {
// Add static id maps to host or library resources and map it later at
// compile-time with the aapt-generated `resources.arsc' and `R.java' file
staticIdMaps.put(be.id, le.id)
staticIdStrMaps.put(be.idStr, le.idStr)
if (be.key == 'tv_title' && be.type == 'id') {//重復(fù)id bug
retainedEntries1.add(be)
}
return
}
這里通過k過濾重復(fù)資源,我們新建一個(gè)retainedEntries1重新加入,然后在后面遍歷生成retainedTypes1
def retainedTypes1 = []
currType = null
retainedEntries1.each { e ->
// Prepare entry id maps for resolving resources.arsc and binary xml files
if (currType == null || currType.name != e.type) {
// New type
currType = [type: e.vtype, name: e.type, id: e.typeId, _id: e._typeId, entries: []]
retainedTypes1.add(currType)
}
def newResId = pid | (e._typeId << 16) | e._entryId
def newResIdStr = staticIdStrMaps[e.idStr]
//這里通過staticIdStrMaps獲取而不是"0x${Integer.toHexString(newResId)}"的形式
def entry = [name: e.key, id: e.entryId, _id: e._entryId, v: e.id, _v: newResId,
vs : e.idStr, _vs: newResIdStr]
currType.entries.add(entry)
}
...
small.retainedTypes1 = retainedTypes1
上面newResIdStr要沖staticIdStrMaps(從已有的獲?。?。通過上面代碼就可以獲得包含重復(fù)id(tv_title)的type列表了,然后生成插件R文件的retainedTypes改成retainedTypes1。
// Also generate a split edition for later re-compiling
aapt.generateRJava(small.splitRJavaFile, pkg,
small.retainedTypes1, small.retainedStyleables)
最終分析buildBundle產(chǎn)生的so文件,我們便可以發(fā)現(xiàn)R文件的id列表就有tv_title字段了。
buildBundleIds任務(wù)
之前我們只是簡(jiǎn)單的通過tv_title來判斷重復(fù)的id,但是我們需要所有的重復(fù)id,因此我們需要?jiǎng)?chuàng)建一個(gè)任務(wù),遍歷獲取app.xxx下布局文件所有的id,將這些id保存起來。我們仿照CleanBundleTask.groovy新建一個(gè)BuildBundleIdsTask。
class BuildBundleIdsTask extends DefaultTask {
Set<String> ids = new HashSet<>()
@TaskAction
def run() {
File buildDir = project.projectDir
def sTime = System.currentTimeMillis()
def layoutDir = new File(buildDir, "src/main/res/layout")
def files = layoutDir.listFiles()
for (def f : files) {
findIds(f)
}
writeToFile()
def eTime = System.currentTimeMillis()
println(buildDir.toString() + "======time:" + (eTime - sTime))
}
def writeToFile(){
File idsFile = new File(project.projectDir,"ids.txt")
FileWriter fw = new FileWriter(idsFile)
for(String id:ids){
fw.write(id)
fw.write("\r\n")
}
fw.flush()
fw.close()
}
def findIds(File layoutFile) {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance()
XmlPullParser xmlPullParser = factory.newPullParser()
InputStream inputStream = new FileInputStream(layoutFile)
xmlPullParser.setInput(inputStream, "UTF-8")
int eventType = xmlPullParser.getEventType()
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
int count = xmlPullParser.getAttributeCount();
for (int i = 0; i < count; i++) {
String name = xmlPullParser.getAttributeName(i)
String value = xmlPullParser.getAttributeValue(i)
if(name == 'android:id'){
value = value.substring(value.lastIndexOf("/")+1)
ids.add(value)
}
}
}
eventType = xmlPullParser.next()
}
}
}
通過XmlPullParser解析xml文件,獲取id,然后保存到ids.txt文件中。
通過buildBundleId任務(wù)生成ids.txt,之前的tv_title邏輯可以改一下了。
private void findBundleIds(Set<String> bundleIds) {
File file = new File(project.projectDir, "ids.txt")
if (!file.exists()) return
FileReader reader = new FileReader(file)
String id = null
while ((id = reader.readLine()) != null) {
bundleIds.add(id)
}
reader.close()
}
/**
* Prepare retained resource types and resource id maps for package slicing
*/
protected void prepareSplit() {
def idsFile = small.symbolFile
if (!idsFile.exists()) return
Set<String> bundleIds = new HashSet<>()
findBundleIds(bundleIds)
...
bundleEntries.each { k, Map be ->
...
le = libEntries.get(k)
if (le != null) {
// Add static id maps to host or library resources and map it later at
// compile-time with the aapt-generated `resources.arsc' and `R.java' file
staticIdMaps.put(be.id, le.id)
staticIdStrMaps.put(be.idStr, le.idStr)
if (bundleIds.contains(be.key) && be.type == 'id') {//重復(fù)id bug
retainedEntries1.add(be)
}
return
}
...
}
}
這樣在生成ids.txt后,我們buildBundle生成是插件里的R文件就會(huì)有重復(fù)id了。