Android程序的基本组件有4个,分别为:Activity,BroadcastReceiver,ContentProvider和Service。
Activity(活动窗口):
Activity是程序和用户交互的界面,是Android程序中最基本的模块。一个Android程序可以拥有一个或多个Activity。Activity可以和layout文件夹下的xml布局文件对应对Activity内部的组件进行设置和布局。
如我们可以在xml中设置两个TextView组件并输出两个字符串:
<TextView
android:id="@+id/hello"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_below="@+id/hello"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is a Android App" />
而在Activity中不做任何修改。
运行结果如下:
这个界面就是一个Activity,内部组件由xml布局文件和该Activity的java文件共同决定(可以在java文件中添加组件)。
BroadcastReceiver(广播接收器)
用于接收广播通知信息,并做出对应的处理的组件。大部分广播信息都来自于系统如电池电量低,更改某些设定(如语言选项)等等,当然Android程序也可以进行广播。
默认BroadcastReceiver代码如下:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context,Intent intent) {
// TODO: This method is called when theBroadcastReceiver is receiving
// an Intent broadcast.
throw newUnsupportedOperationException("Not yet implemented");
}
}可以看出所有的BroadcastReceiver都继承了BroadcastReceiver类。
Content Provider(数据共享)
Content Provider用于提供数据共享,它将一些数据提供给其他程序使用。共享数据的实现需要基础ContentProvider类。BroadcastReceiver提供了整套标准方法,但应用程序通常通过使用ContentResolver对象来代替。
Service(服务)
Service没有可视化的用户界面,而是在一段时间内在后台运行。如可以在后台获取网络数据。所有服务都必须继承Service类。创建的Server类默认代码如下:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
本文详细介绍了Android应用开发中的四大核心组件:Activity、BroadcastReceiver、ContentProvider和服务(Service)。每个组件的作用及其基本用法都有所涉及。
2504

被折叠的 条评论
为什么被折叠?



