android中的BroadcastReceiver简单用法

时间:2023-01-30 08:35:59
  在xml文件中注册一个按钮
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送广播"/>
给按钮添加事件:
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MyBroadcastReveiver.class);
intent.putExtra("name","jack");
sendBroadcast(intent);
}
});
注册广播接受者:
public  class MyBroadcastReveiver extends BroadcastReceiver {    public void onReceive(Context context, Intent intent){        String string = intent.getStringExtra("name");        Toast.makeText(context,"Hello world" + string,Toast.LENGTH_SHORT).show();    }}
这样就完成了发送广播的功能
android中的BroadcastReceiver简单用法