Android打包jar

问题1:怎么将android java类打包成jar

解决:

解决的方式,在Android Studio上只能通过写gradle脚本来完成,在build.gradle中,编写脚本,之后点击: gradle–>other–>make jar即可

脚本如下:

def _BASENAME = "TestJar";
def _VERSION = "_V1.0";
def _DestinationPath = "build"; //生成jar包的位置
def zipFile = file('build/intermediates/bundles/default/classes.jar'); //待打包文件位置

task deleteBuild(type:Delete){
    delete _DestinationPath + _BASENAME + _VERSION + ".jar"
}

task makeJar(type:Jar){
    from zipTree(zipFile)
    from fileTree(dir:'src/main',includes:['assets/**']) //将assets目录打入jar包  
    baseName = _BASENAME + _VERSION
    destinationDir = file(_DestinationPath)
}

makeJar.dependsOn(deleteBuild, build)

问题2: 如何打包指定包或类中的java到jar包中

解决:

脚本如下:

task clearJar(type: Delete) { 
    delete 'libs/sdk.jar' 
} 

task makeJar(type:org.gradle.api.tasks.bundling.Jar) {
    //指定生成的jar名
    baseName 'sdk'
    //从哪里打包class文件
    from('build/intermediates/classes/debug/org/cmdmac/cloud/pluginsdk/')
    //打包到jar后的目录结构 
    into('org/cmdmac/cloud/pluginsdk/')
    //去掉不需要打包的目录和文件 
    exclude('test/', 'BuildConfig.class', 'R.class')
    //去掉R$开头的文件 
    exclude{ it.name.startsWith('R$');} 
} 

makeJar.dependsOn(clearJar, build)

或者

task makeSdkJar(type:org.gradle.api.tasks.bundling.Jar) {
    baseName 'pluginsdk'
    //只打包org.cmdmac下的org.cmdmac.pluginsdk.impl和org.cmdmac.gamecenter,其他子包不会被打包进去
    from('build/intermediates/classes/debug/org/cmdmac/') {
        include 'pluginsdk/impl'
        include 'gamecenter'
    }
    into('org/cmdmac/')
//    exclude('R.class')
//    exclude{ it.name.startsWith('R$');}
}

你可能感兴趣的:(问题解决)