效果是:一个MainActivity动态注册一个BroadcastReceiver,BActivity发送一个标准广播,MainActivity接收到广播后,将广播中的消息显示在MainActivity的TextView上。
MainActivity:
(实现端)
public class MainActivity extends AppCompatActivity implements IUpdateNumLitener{
private TextView mNumTextView;
private Button mStartButton;
//广播接收器
private NumReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//3、注册广播---哪个画面需要监听广播,在哪个画面注册
mReceiver = new NumReceiver();
//4-3 在实现端实现接口,并把接口传给触发端
mReceiver.setUpdateNumLitener(this);
IntentFilter filter = new IntentFilter();
filter.addAction("org.mobiletrain.add");
registerReceiver(mReceiver, filter);
mNumTextView = (TextView)findViewById(R.id.num_textview);
mStartButton = (Button)findViewById(R.id.start_button);
mStartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
//3 取消注册
unregisterReceiver(mReceiver);
}
@Override
public void getText( String txt) {
mNumTextView.setText(txt);
}
}
BActivity
public class BActivity extends AppCompatActivity {
private Button mAddButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
mAddButton = (Button)findViewById(R.id.add_button);
mAddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add();
}
});
}
private void add() {
//1、发送广播
Intent intent = new Intent("org.mobiletrain.add");
intent.putExtra("key","内容");
sendBroadcast(intent);
}
}
广播接收器BroadcastReceiver
(触发端)
public class NumReceiver extends BroadcastReceiver {
private IUpdateNumLitener iUpdateNumLitener;
@Override
public void onReceive(Context context, Intent intent) {
String txt = intent.getStringExtra("key");
iUpdateNumLitener.getText(txt);
}
//4-3 在实现端实现接口,并把接口传给触发端
//接收接口的方法
public void setUpdateNumLitener (IUpdateNumLitener updateNumLitener) {
this.iUpdateNumLitener = updateNumLitener;
}
}
接口
//4-1 定义接口,封装抽象方法
public interface IUpdateNumLitener {
void update();
}