想要將一個(gè)項(xiàng)目導(dǎo)出為jar包,供其它項(xiàng)目使用,在eclipse中可以直接導(dǎo)出該項(xiàng)目為jar包,而 在AS中可以通過修改gradle才處理。
接下來就介紹下具體的步驟:
1、新建一個(gè)項(xiàng)目,項(xiàng)目名隨意,eg:MakeJarApplication,在項(xiàng)目中新建一個(gè)module類型為android-library ,命名為testLibrary。如圖:

項(xiàng)目結(jié)構(gòu)圖
2、讓app依賴這個(gè)庫(kù),在app下的build.gradle文件中添加compile project(':testlibrary')
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) 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' compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4' testCompile 'junit:junit:4.12' compile project(':testlibrary')}3、在testlibrary中創(chuàng)建一個(gè)TestShow類讓外部的app能調(diào)用。并在app中調(diào)用
(1)TestShow .java
public class TestShow { public void show(Context context, String msg, TextView textView) { textView.setText(msg); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } public void test() { System.out.println("測(cè)試信息,test()方法"); }}(2)、MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show_tv = ((TextView) findViewById(R.id.show_tv)); ((Button) findViewById(R.id.btn)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new TestShow().show(MainActivity.this, "調(diào)用jar包中的show方法", show_tv); } }); }4、testlibrary的build.gradle中配置能生成jar文件:
def SDK_BASENAME = "TestSdk";def SDK_VERSION = "_V1.0";def sdkDestinationPath = "build";def zipFile = file('build/intermediates/bundles/default/classes.jar')task deleteBuild(type: Delete) { delete sdkDestinationPath + SDK_BASENAME + SDK_VERSION + ".jar"}task makeJar(type: Jar) { from zipTree(zipFile) from fileTree(dir: 'src/main',includes: ['assets/**'])//將assets目錄打入jar包 baseName = SDK_BASENAME + SDK_VERSION destinationDir = file(sdkDestinationPath)}makeJar.dependsOn(deleteBuild, build) 其中SDK_BASENAME = "TestSdk"; SDK_VERSION = "_V1.0"; 是定義生成jar的名字為TestSdk_V1.0.jar。
5、在右側(cè)的Gradle目錄中有個(gè)“other”,展開找到“makejar”,然后雙擊“makejar”,就可以生成jar文件了,生成結(jié)果如下:

步驟結(jié)果導(dǎo)圖
現(xiàn)在就可以復(fù)制TestSdk.jar到一個(gè)新的module中的libs目錄下,然后就可以調(diào)用 new TestShow().show(context, "", show_tv);方法了。
6、在項(xiàng)目中調(diào)用結(jié)果:

總結(jié)
以上所述是小編給大家介紹的Android Studio 生成自定義jar包的步驟詳解,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注