最近在unity3d项目中接入讯飞语音sdk,以前接安卓sdk的时候,一般是使用eclipse的adt进行构建,在adt上生成jar很方便,直接导出就是了,而在android studio中生成jar,其实也很方便,不过需要敲几行gradle脚本命令,使用gradle中的一种task脚本命令生成jar,之后生成jar也是直接点击运行对应的task就可以了。
打开app目录下的build.gradle文件,添加以下生成jar的命令:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | task delete_old_helloworld_jar(type: Delete) { delete 'build/libs/HelloWorld.jar' //先删除之前生成的jar包 } task build_helloworld_jar(type: Jar, dependsOn: ['delete_old_helloworld_jar', 'build']) { archiveName = 'HelloWorld.jar' //jar包的名字 from('build/intermediates/classes/release') //把这个目录下的东东编译成jar包 destinationDir = file('build/libs') //编译出的jar包的输出目录 exclude('com/yly/helloworld/BuildConfig.class') //过滤多余的class文件 exclude('com/yly/helloworld/BuildConfig\$*.class') //过滤多余的class文件 exclude('**/R.class') //过滤多余的class文件 exclude('**/R\$*.class') //过滤多余的class文件 include('com/yly/helloworld/**') //包含需要打包到jar中的文件 } |
完整的build.gradle文件内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | //apply plugin: 'com.android.application' apply plugin: 'com.android.library' android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { //applicationId "com.yly.helloworld" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" //testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.3.1' testCompile 'junit:junit:4.12' } task delete_old_helloworld_jar(type: Delete) { delete 'build/libs/HelloWorld.jar' //先删除之前生成的jar包 } task build_helloworld_jar(type: Jar, dependsOn: ['delete_old_helloworld_jar', 'build']) { archiveName = 'HelloWorld.jar' //jar包的名字 from('build/intermediates/classes/release') //把这个目录下的东东编译成jar包 destinationDir = file('build/libs') //编译出的jar包的输出目录 exclude('com/yly/helloworld/BuildConfig.class') //过滤多余的class文件 exclude('com/yly/helloworld/BuildConfig\$*.class') //过滤多余的class文件 exclude('**/R.class') //过滤多余的class文件 exclude('**/R\$*.class') //过滤多余的class文件 include('com/yly/helloworld/**') //包含需要打包到jar中的文件 } |
写完后,展开右边的“Gradle”选项,双击运行“build_helloworld_jar”选项:
过一会,就会在build/libs目录下生成我们需要的jar包啦:
android studio加入第三方jar包就比eclipse方便很多,直接ctrl + c复制jar文件,然后ctrl + v粘贴到app/libs目录下,然后选中该jar包右键选择“Add As Library”选项即可