使用Eclipse开发Android专案时,开发人员能够将可重用的程式码,封装为Library来提供其余开发人员使用。本篇文章介绍如何将可重用的程式码封装为Library,主要为本身留个纪录,也但愿能帮助到有须要的开发人员。javascript
先开启Eclipse来创建一个新专案:「myLibrary」,勾选「Mark this project as a library」用来标注新专案为Library类型,而且取消暂时用不到的两个选项:「Create custom launcher icon」、 「Create Activity」。以后这个专案就能够用来封装可重用的程式码,提供其余开发人员使用。java
创建专案android
创建设定web
接着在MyLibrary加入一个新类别:「MyClass」,作为提供给其余开发人员使用的程式码。app
MyClass.javaide
package myLibrary; public class MyClass { // methods public String getMessage () { return "Clark" ; } }
创建类别以后,只要存档而且编译专案,就能够在专案的bin目录下取得编译完成的myLibrary.jar。ui
产出myLibrary.jarthis
接着开启Eclipse来创建一个新专案:「myAPP」,这个专案用来讲明,如何使用封装为Library的程式码。spa
创建专案3d
创建设定
再来在专案的lib目录上点击滑鼠右键开启Import对话框,而且选取File System。
开启Import对话框
选取File System
接着选择先前所创建的myLibrary下的bin目录,把myLibrary.jar加入到目前专案里。
加入myLibrary.jar
完成设定步骤以后,接着在专案预设的MainActivity.java档里面,加入下列程式来使用Library里面所封装的程式码。
加入Library参考
import myLibrary.MyClass;
使用Library中的程式码
// test MyClass x = new MyClass(); String message = x.getMessage();
完整的MainActivity.java
package com.example.myapp; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.os.Bundle; import myLibrary.MyClass; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // super super .onCreate(savedInstanceState); // init setContentView(R.layout.activity_main); // test MyClass x = new MyClass(); String message = x.getMessage(); // alert Builder alert = new AlertDialog.Builder( this ); alert.setMessage(message); alert.show(); } }
最后,执行MyAPP。能够在执行画面上,看到一个Alert视窗显示从Library取得的讯息内容,这也就完成了使用Library的相关开发步骤。
显示回传讯息