Android development - Gradle JarJar plugin

    While developing our Mobile Bank, we once encountered such a problem .

    Namely: when using the GSON library to serialize / deserialize to / from JSON on some HTC devices in runtime, we got crashes. The reason for this behavior is that some HTC devices have their own version of GSON in their firmware, which is older than the one we used in our projects. And the android java class loader, when loading the class into memory, prefers the “system” version, instead of the version in the project.

    In addition, on some devices there is a similar problem with OkHttp, which is also a fairly popular library in the world of android development.

    To solve the problem, you need to repackage GSON (or any other library) using the JarJar utility. After repackaging, the artifact will have a new package structure, which must be used in import directives in your project. To do this, you need to connect the repackaged jar to your project instead of the original one.

    We wanted to automate this task and as a result, the Gradle JarJar Plugin appeared , available in Maven Central . The plugin allows you to specify jar libraries and rules for repackaging them using JarJar.



    Add the plugin to the dependencies of the script:

    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'ru.tinkoff.gradle:jarjar:1.1.0'
        }
    }
    

    We connect it in the project module:

    apply plugin: 'ru.tinkoff.gradle.jarjar'
    

    Specify a list of artifacts for repackaging:

    dependencies {
        // Будет переупаковано с помощью JarJar
        jarJar 'com.google.code.gson:gson:2.3'
        // Результаты работы плагина находятся в build/libs, добавляем их в classpath проекта
        compile fileTree(dir: './build/libs', include: ['*.jar'])
    }
    

    Customize:

    jarJar {
        // Опциональный параметр - jarJar.jar используемый для переупаковки jar :)
        jarJarDependency 'com.googlecode.jarjar:jarjar:1.3'
        // Список правил
        // первый параметр - имя артефакта, указанного в скоупе jarJar в dependencies проекта
        // второй - правила для JarJar
        rules = ['gson-2.3.jar': 'com.google.gson.** ru.tinkoff.core.gson.@1']
    }
    

    Also popular now: