package com.example.ch10_broadcast;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button send;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取程序界面中的按钮
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 创建Intent对象
Intent intent = new Intent();
// 设置Intent的Action属性
intent.setAction("org.crazyit.action.CRAZY_BROADCAST");
intent.putExtra("msg", "胡斐发送的简单的消息");
// 发送广播
sendBroadcast(intent);
}
});
}
}
MyReceiver.java
/**
* ChinaEdu.com Inc.
* Copyright (c) 1999-2015 All Rights Reserved.
*/
package com.example.ch10_broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
*
* @author hufei
* @version $Id: MyReceiver.java, v 0.1 2015-5-4 下午2:42:53 hufei Exp $
*/
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();
}
}
AndroidManifest.xml:
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="org.crazyit.action.CRAZY_BROADCAST" />
</intent-filter>
</receiver>
activity_main.xml
<?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="@string/send" />
</LinearLayout>