Android中的消息传递——Intent简介

1  Intent

l  Intent是一种传递消息的机制,一个Intent的对象常常包括ACTION和DATA,通过Intent MyIntent = new Intent(string MyAction)就可以创建一个名叫MyIntent, ACTION是MyAction的Intent对象.

l  Intent中还可以通过MyIntent.putExtra(string)来附加更多的信息.

l  Intent的目的在于传递, 传递的过程通过sendBroadcast(MyIntent)来将这个Intent广播出去.

 

2  BroadcastReceiver

l  一个Intent被广播出去之后, 要有接收端, 这个接收端就是BroadcastReceiver, 定义如下:

public class MyReceiver extendsBroadcastReceiver{
@Override
         publicvoid onReceiver(Context context, Intent intent){
                   /*接受Intent之后的操作 */
}


l  定义了MyReceiver之后,要在AndroidManifest.xml中注册才会其作用, 注册的方式如下:

<receiverandroid:name=”MyReceiver”>
</receiver>


l  一般还会给每个BroadcastReceiver设置一个Intent Filter对某些特定的Intent作出反应,比如MyReceiver希望对上面MyAction做出反应,注册时如下:

<receiverandroid:name=”MyReceiver”>
<intent-filter>
<actionandroid:name=MyAction/>
</intent-filter>
</receiver>


 

3  Process

(1)  定义一个BroadcastReceiver并注册, 设置intentfilter接受包含提前约定的ACTION的intent

(2)  创建一个包含提前约定的ACTION的intent,使用sendBroadcast()广播出去

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值