android studio使用gradle自定义导出jar文件

在android studio中导出jar文件并不像在eclipse那样简单,不过也不是太复杂。须要用到gradle脚原本导出jar文件。android

咱们不但愿导出的jar文件带有R.class和BuildConfig.class这样的类,因此咱们须要编写gradle脚原本实现自定义jar文件内容。app

先打开module项目下的build.gradle文件,在android{}标签下编写task命令,以下是个人gradle文件:eclipse

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.testapp"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

task buildMyJar(type: Jar, dependsOn: ['build']) {
    //导出的jar文件名称
    archiveName = 'TestApp.jar'
    //从哪一个目录打包jar
    from('build/intermediates/classes/debug')
    //导出的jar文件的存放目录(未指定则默认存放在build/libs下)
    destinationDir = file('build/libs')
    //去掉不要的类
    exclude('com/example/testapp/BuildConfig.class')
    exclude('com/example/testapp/BuildConfig\$*.class')
    exclude('**/R.class')
    exclude('**/R\$*.class')
    //须要打包的类
    include('com/example/testapp/*.class')
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.google.android.gms:play-services-appindexing:8.1.0'
}

若是须要将assets文件夹也打包进jar文件,则可在buildMyJar 任务中加入一下两行:gradle

from fileTree(dir: 'src/main',includes: ['assets/**'])
include('assets/**')

写好gradle脚本后点击“sync now”ui

打开android studio右侧的Gradle面板,选择项目名——>other——>buildMyJar(task名称)google

双击后运行该脚本,就会在build/libs目录下生成jar文件。用jd-gui打开该jar文件能够看到里面的class文件没有包含R.class之类的文件spa

 

 

相关文章
相关标签/搜索