首页 > 代码库 > Android -- 简单广播接收与发送(1)

Android -- 简单广播接收与发送(1)

1. 效果图

 

2. 实现代码 

 layout.xml

 

 <Button        android:id="@+id/testBtn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/hello_world" />

 

  MainActivity.java

public static final String MY_ACTION = "iflab.test.MY_ACTION"; // 自定义ACTION	private Button testBtn;	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		testBtn = (Button) findViewById(R.id.testBtn);		testBtn.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View v) {				// TODO Auto-generated method stub				Intent intent = new Intent();				intent.setAction(MY_ACTION);				intent.putExtra("message", "来自于广播的消息!"); // 设置广播的消息				sendBroadcast(intent);			}		});	}

 testBroadcastReceiver.java

public class testBroadcastReceiver extends BroadcastReceiver {	// context 上下文对象 intent 接收的意图对象	@Override	public void onReceive(Context context, Intent intent) {		// TODO Auto-generated method stub		String str;		str = "接收到的广播消息为:" + intent.getStringExtra("message"); // 接收消息		Toast.makeText(context, str, Toast.LENGTH_SHORT).show();	}}

 配置文件中需要填写的信息

 <receiver android:name="testBroadcastReceiver" >            <intent-filter>                <action android:name="iflab.test.MY_ACTION" />            </intent-filter>        </receiver>

 

3. 说明

 <action android:name="iflab.test.MY_ACTION" />  为你在 MainActivity 中定义的常量
<receiver android:name="testBroadcastReceiver" >   name 的值为 你要接收广播的时候所启动的类  testBroadcastReceiver

 

Android -- 简单广播接收与发送(1)