网上找了好多资料,发现还是没有制作成功,各种报错,看到烦,最后自己从头做了个简单的Test,总算是完工了!
本文仅供以后查看,怕忘记!
平台环境:Android Studio 3.1
目的:Test打进jar包里,让app实现调用;
1.首先创建一个new project,选择一个empty activity,然后finish;
2.第二步,就是在app目录下的src/main/java下,创建一个Test package,在package里创建两个类,一个TestPrint,一个TestDoWith;
public abstract class TestPrint { public abstract String print(); }
public class TestDoWith extends TestPrint { @Override public String print(){ String strTemp = "Use it Successed!"; return strTemp; } }
3.再MainActivity里面调用一下,run一下
TestPrint testPrint; TextView tv_Title; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); testPrint = new TestDoWith(); tv_Title.setText(testPrint.print()); } private void initView(){ tv_Title = findViewById(R.id.TV_Title); }
看会不会显示
"Use it Successed!"
这样就说明TestPackage包是能正常使用的;
下面就开始把Test package打包成jar:
1.首先还是老方法,在app同级目录下创建一个新的Module,选择类型是library,直到finish完成。
我就创建了一个mylibrary,如上图所示:
2.然后把app/src/main/java里面的新建的package里面的两个类,剪切进如图:
然后删除掉app里面的package一项。
3.修改mylibrary目录下的build.gradle文件,如下:
def BASENAME = "Test"; def VERSION = "_V1.0"; def DestinationPath = "build"; task delete(type: Delete) { delete DestinationPath + BASENAME + VERSION + ".jar" } task makeJar(type: Jar) { from('build/intermediates/classes/debug/com/realid/mylibrary/TestDoWith.class','build/intermediates/classes/debug/com/realid/mylibrary/TestPrint.class') into('') baseName = BASENAME + VERSION destinationDir = file(DestinationPath) } makeJar.dependsOn(delete, build)
这个时候要注意了:在task makeJar里面的from,网上找到的基本上都是('build/intermediates/bundles/***/***'),你会发现在目录下根本就没有,其实你只要打包你所要打包的那个类就可以了这里我就打包了
com/realid/mylibrary/TestDoWith.class','build/intermediates/classes/debug/com/realid/mylibrary/TestPrint.class')
同时要注意:别把BuildConfig.class以及R.class也一起打包进来了。编译的时候会报错。
同时提醒:在project目录下出现了变化:(build.gradle可以看到加进了如下几行)
allprojects { repositories { google() jcenter() } }这几行很关键,如果没有这几行,mylibrary下的
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:27.1.1' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' }
会产生报错。
4.在平台的右侧Gradle下,选择如下图所示:
执行makeJar,成功之后,如下图:
这样就成功生成了jar包了。
5.最后就是在app目录下的build.gradle添加如下
compile project(':mylibrary')
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.0.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' compile project(':mylibrary') }
就可以在MainActivity里面调用Test里面的print函数了
如果是自己用jni生成so库的,package名要一致就可以了
版权声明:https://blog.csdn.net/KingOTG/article/details/79882070