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

 

 

相關文章
相關標籤/搜索