从名字中大概就知道了意思,BroadcastReceiver就是广播接收器的意思,它运行在后台,始终处于监听的状态,当有系统消息或用户自定义的消息到达时,回调onReceiver()函数,着这个例子中,我只是在这个回调函数中打印出一句话,复杂的BroadcastReceiver操作下文会介绍。
下面的截图就是程序运行的实例:
下面是这个例子所用到的源代码:
public class BroadcastReceiver01 extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast_receiver01);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent("BruceZhang");
BroadcastReceiver01.this.sendBroadcast(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_broadcast_receiver01, menu);
return true;
}
}
public class Broadcast_receiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.d("BruceZhang", "This is BroadcastReceiver!!!");
}
}