使用Eclipse开发Android项目时,开发人员可以将可重用的程序代码,封装为Library来提供其他开发人员使用。本篇文章介绍如何将可重用的程序代码封装为Library,主要为自己留个纪录,也希望能帮助到有需要的开发人员。
先开启Eclipse来建立一个新项目:「myLibrary」,勾选「Mark this project as a library」用来标注新项目为Library类型,并且取消暂时用不到的两个选项:「Create custom launcher icon」、「Create Activity」。之后这个项目就可以用来封装可重用的程序代码,提供其他开发人员使用。
建立项目
建立设定
接着在MyLibrary加入一个新类别:「MyClass」,做为提供给其他开发人员使用的程序代码。
MyClass.java
package myLibrary;
public class MyClass {
// methods
public String getMessage()
{
return "Clark";
}
}
建立类别之后,只要存盘并且编译项目,就可以在项目的bin目录下取得编译完成的myLibrary.jar。
产出myLibrary.jar
接着开启Eclipse来建立一个新项目:「myAPP」,这个项目用来说明,如何使用封装为Library的程序代码。
建立项目
建立设定
再来在项目的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的相关开发步骤。
显示回传讯息
原文:http://www.cnblogs.com/clark159/p/5007419.html