二、Hello world示例
为了叙述方便,我们先给出一个简单的hello world程序。工程的目录结构如下:
|-- AndroidManifest.xml
|-- assets
|-- bin
|-- default.properties
|-- res
| |-- drawable
| | `-- icon.png
| |-- layout
| | `-- main.xml
| `-- values
| `-- strings.xml
`-- src
`-- hello
`-- world
`-- hello.java
|-- assets
|-- bin
|-- default.properties
|-- res
| |-- drawable
| | `-- icon.png
| |-- layout
| | `-- main.xml
| `-- values
| `-- strings.xml
`-- src
`-- hello
`-- world
`-- hello.java
我使用的开发环境是eclipse及adt0.9和OPhone sdk 1.5。上图中所有文件和目录都是根据建立工程时的配置自动生成的。hello.java是我在这个工程中唯一修改的地方,在程序执行时会在屏幕上显示 “hello, OPhone”的字样。源码如下,注意粗体为修改的代码。
package hello.world;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class test extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView test = new TextView(this);
Test.setText(“hello, OPhone”);
setContentView(test);
}
}
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class test extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView test = new TextView(this);
Test.setText(“hello, OPhone”);
setContentView(test);
}
}
使用eclipse编译之后可以看到工程的目录结构发生了变化。bin和gen目录是编译之后产生的。
|-- AndroidManifest.xml
|-- assets
|-- bin
| |-- classes.dex
| |-- hello
| | `-- world
| | |-- R$attr.class
| | |-- R$drawable.class
| | |-- R$layout.class
| | |-- R$string.class
| | |-- R.class
| | `-- hello.class
| |-- helloworld.apk
| `-- resources.ap_
|-- default.properties
|-- gen
| `-- hello
| `-- world
| `-- R.java
|-- res
| |-- drawable
| | `-- icon.png
| |-- layout
| | `-- main.xml
| `-- values
| `-- strings.xml
`-- src
`-- hello
`-- world
`-- hello.java
|-- assets
|-- bin
| |-- classes.dex
| |-- hello
| | `-- world
| | |-- R$attr.class
| | |-- R$drawable.class
| | |-- R$layout.class
| | |-- R$string.class
| | |-- R.class
| | `-- hello.class
| |-- helloworld.apk
| `-- resources.ap_
|-- default.properties
|-- gen
| `-- hello
| `-- world
| `-- R.java
|-- res
| |-- drawable
| | `-- icon.png
| |-- layout
| | `-- main.xml
| `-- values
| `-- strings.xml
`-- src
`-- hello
`-- world
`-- hello.java
在gen目录下生成了R.java文件,这是系统根据资源文件生成的。在bin目录下生成了6个.class文件,记住这一点。另外bin目录下还生成了helloworld.apk,下面我们就来分析这个文件。