Android中的四大基本组件及简单使用说明

本文介绍了Android应用开发中的四大基本组件:Activity、Service、BroadcastReceiver及Content Provider,并详细解释了每个组件的功能及其使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android应用开发四大基本组件为:ActivityServiceBroadcast Receiver以及Content Provider。这四大组件除了Broadcast Receivers是在运行时创建外,其他都需要在Manifest中声明。比如Activity<activity>Service<service>Broadcast Receiver<receiver>Content Provider<provider>

一、关于Activity:这就必须讲到Intent了,它可以实现从一个Activity跳转到另一个Activity,它有两种(事实上不止两种,但是这两种比较重要)方式:

(1)       Intent intent = new Intent(activity1.this, activity2);

startActivity(intent);

(2)       Intent intent = new Intent();

intent.setAction(xx);

intent.setType(yy);

intent.setCategory(zz);

startActivity(intent);

              以上的intentset的内容对应到Manifest文件中<intent-filter></intent-filter>之间的内容,比如setAction对应到<action>里面的内容。

二、关于Service。它分两步,第一步是在Manifest文件中声明,第二步是extends Service。同时Service分为本地Service以及远程Service

1)本地Service:启动方法为:startService(Intent)

2)远程Service

       它用bindService方法启动,该方法会连接到一个正在运行的Service,在必要时创建Service并在连接后返回truebindService会导致调用onCreate()方法,随后会调用onBind()函数,该函数会返回用于跟Service交互的通信通道(实现IBinder接口的类的实例)。简单举例如下:

Public class SimpleService extends Service

{

       Public class SimpleBinder extends Binder

{

       SimpleService getService()

       {    

              Return SimpleService.this;

}

}

Private final IBinder binder = new SimpleBinder();

Public IBinder onBind(Intent intent)

{

       Return binder;

}

Public void onCreate(){}

Public void onDestroy(){}

}

 

然后在具体的ActivityonCreate(Bundle)方法中包含下面的代码:

ServiceConnection sc = new ServiceConnection()

{

       Public void onServiceConnected(ComponentName className, IBinder service)

{    

       SimpleService ss = ((SimpleService.SimpleBinder)service).getService();

}

Public void onServiceDisconnected(ComponentName className)

{

}

}

bindService(new Intent(SImpleActivity.this, SimpleService.class), sc. Context.BIND_AUTO_CREATE);

以上的过程简述为:onBind中返回的binder->继承Binder的类->类中定义的方法

三、关于Broadcast Receiver:具体的方法简单说明如下:首先是定义一个类继承BroadcastReceiver类;然后重载其onReceived()方法,该方法指的是接收到广播后的处理。最后就是在某个Activity类中通过sendBroadcast(intent)指到刚才定义的类中。简单举例如下:

Public class MyBroadcastReceiver extends BroadcastReceiver

{

       Public void onReceive(Context context, Intent intent){

              //具体处理

}

}

然后就是在某一情况下触发该事件:

Btn.setOnClickListener(new OnClickListener(){

       Public void onClick(View v){

       Intent it = new Intent(NEW_LISRFORM_DETECTED);

       sendBroadcast(it);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值