android api分析26 BroadcastReceiver例子

本文介绍如何在Android应用中实现发送有序广播并由多个接收者接收的流程,包括创建Intent、设置Action、发送广播以及接收者如何响应广播。通过实例演示了如何在应用程序中使用有序广播进行数据传递。
public class MainActivity extends Activity
{
	Button send;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 获取程序中的send按钮
		send = (Button) findViewById(R.id.send);
		send.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// 创建Intent对象
				Intent intent = new Intent();
				intent.setAction("org.crazyit.action.CRAZY_BROADCAST");
				intent.putExtra("msg" , "简单的消息");
				// 发送有序广播
				sendOrderedBroadcast(intent , null);
			}	
		});
	}
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/send"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="send" />

</LinearLayout>
public class MyReceiver extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent)
	{

		Toast.makeText(context , "接收到的Intent的Action为:"
			+ intent.getAction() 
			+ "\n消息内容是:" + intent.getStringExtra("msg")
			, 5000)
			.show();
		// 创建一个Bundle对象,并存入数据
		Bundle bundle = new Bundle();
		bundle.putString("first" , "第一个BroadcastReceiver存入的消息");
		// 将bundle放入结果中
		setResultExtras(bundle);
		// 取消Broadcast的继续传播
//		abortBroadcast();
	}
}
public class MyReceiver2 extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent)
	{
		Bundle bundle = getResultExtras(true);
		// 解析前一个BroadcastReceiver所存入的key为first的消息
		String first = bundle.getString("first");
		Toast.makeText(context , "第一个Broadcast存入的消息为:"
			+ first	, 5000)
			.show();		
	}
}
<receiver android:name=".MyReceiver">
			<intent-filter android:priority="20">
				<action android:name="org.crazyit.action.CRAZY_BROADCAST" />
			</intent-filter>		
		</receiver>
		<receiver android:name=".MyReceiver2">
			<intent-filter android:priority="0">
				<action android:name="org.crazyit.action.CRAZY_BROADCAST" />
			</intent-filter>		
		</receiver>	




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值