zoukankan      html  css  js  c++  java
  • BroadCast,BroadCastReceiver

    效果是:一个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();
    }
     
  • 相关阅读:
    git 强制覆盖本地
    给mysql添加账户并且赋予权限
    laravel 地址栏传参不了问题
    订单系统开发02
    熵——信息增益
    熵——导读
    熵——自信息
    tensorflow在文本处理中的使用——skip-gram & CBOW原理总结
    霍夫曼树
    tensorflow在文本处理中的使用——Word2Vec预测
  • 原文地址:https://www.cnblogs.com/niupi/p/5523677.html
Copyright © 2011-2022 走看看