Small插件化重复id的解决方法

前言

在使用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了。

项目地址

https://github.com/iamyours/SmallTest

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,843评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,538评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,187评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,264评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,289评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,231评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,116评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,945评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,367评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,581评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,754评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,458评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,068评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,692评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,842评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,797评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,654评论 2 354

推荐阅读更多精彩内容