Broadcast Receviewer
使用Braodcast Receiver
一.新建一个空的工程,命名为LearnBroadcastReceiver
二.为主界面添加一个按钮
三.新建一个broadcast receiver,命名为MyReceiver,并添加如下所示代码
public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. System.out.println("Received the message,and the message is"+intent.getStringExtra("data")); }
四.在MainActivit.java中设置监听器
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btnSendMessage).setOnClickListener( this); } public void onClick(View v) { switch(v.getId()){ case R.id.btnSendMessage: Intent i = new Intent(this,MyReceiver.class); i.putExtra("data","hello world"); sendBroadcast(i); break; } }
五.运行结果