import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BroadcastMain extends Activity {
Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast_main);
//获取程序界面中的按钮
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 创建Intent对象
Intent intent = new Intent();
//设置Intent的属性
intent.setAction("broadcasttest.action.CRAZY_BROAFCAST");
intent.putExtra("msg", "简单的信息");
//发送广播
sendBroadcast(intent);
}
});
}
}
上面的程序中粗体字代码用于创建一个Intent对象,1并使用该Intent对象对外发送一条广播,该程序所使用的BroadcastReceiver代码如下:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
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();
}
}