前言
在使用smal重构项目时,碰到最大的问题就是业务插件布局id不能和公共库的id重复。如果发生重复就会报java.lang.NoSuchFieldError: com.xxx.xxx.R$id.xxx,这个对项目插件化重构的影响太大了,因为这个太难预测了,你无法知道id重复有哪些,只有一个个调试,发生错误然后重新改id(在重构前期就是这么干的/(ㄒoㄒ)/~~)。因此,必须得将这个问题解决。
解决思路
既然是报NoSuchFieldError,那应该是插件中的R文件没有这个id,使用Android Studio的Analyze Apk打开对应的插件(将so重命名为apk),打开class.dex文件,找到对应的R文件,发现确实是没有那个id。在buildBundle的过程中,有一行日志比较重要
[app.news] split library R.java files... [ OK ]
正如它的表述的意思,拆分R文件成功。因此在生成R文件的过程中,他会将R文件拆分过滤,减少无用的id。我们将Small的编译插件buildSrc引入到项目中,全局搜索“split library R.java files...”,找到了相关的代码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 {
...
}
这里生成了两个R文件,一个是包含所有资源的R文件,一个经过过滤的R文件。
而第二个R文件会最终打包放入插件中。通过断点调试插件,我们可以找到一些关键信息。
生成R文件需要4个参数,我们重点关注第三个参数types。第一个R文件传的是small.allTypes,而另外一个则是smal.retainedTypes(retained:保留;保持;)。这里我们可以通过打印的形式打印出来。发现retainedTypes就只保存了不重复的id。因此,只要我们在生成第二个R文件中把重复的id加入进去即可。
找到重复id
我们需要从allTypes中获取重复id,合并retainedTypes生成一个新的retainedTypes1(为了不干扰,新建一个字段)。在此之前,需要知道retainedType和allTypes是怎么初始化的。通过搜索关键字,调试代码。找到了关键代码
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多行,不过通过调试还是能理清楚的。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()中加入重复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') {//重复id bug
retainedEntries1.add(be)
}
return
}
这里通过k过滤重复资源,我们新建一个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(从已有的获取)。通过上面代码就可以获得包含重复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产生的so文件,我们便可以发现R文件的id列表就有tv_title字段了。
buildBundleIds任务
之前我们只是简单的通过tv_title来判断重复的id,但是我们需要所有的重复id,因此我们需要创建一个任务,遍历获取app.xxx下布局文件所有的id,将这些id保存起来。我们仿照CleanBundleTask.groovy新建一个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任务生成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') {//重复id bug
retainedEntries1.add(be)
}
return
}
...
}
}
这样在生成ids.txt后,我们buildBundle生成是插件里的R文件就会有重复id了。