zoukankan      html  css  js  c++  java
  • 使用Broadcast实现android组件之间的通信

    android组件之间的通信有多种实现方式,Broadcast就是其中一种。在activity和fragment之间的通信,broadcast用的更多本文以一个activity为例。
    效果如图:
    这里写图片描述

    布局文件:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
    
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView1"
            android:layout_marginLeft="27dp"
            android:layout_marginTop="26dp"
            android:text="发送广播" />
    
    </LinearLayout>

    MainActivity.java

    public class MainActivity extends Activity {
    
        private Button btn;
        private TextView tv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tv = (TextView) this.findViewById(R.id.textView1);
    
            //接收广播
            LocalBroadcastManager broadcastManager = LocalBroadcastManager
                    .getInstance(MainActivity.this);
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.example.test1");
            BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    tv.setText("1111");
                }
            };
            broadcastManager.registerReceiver(mItemViewListClickReceiver,
                    intentFilter);
    
            btn = (Button) this.findViewById(R.id.button1);
            btn.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                    //发送广播
                    Intent intent = new Intent("com.example.test1");
                    LocalBroadcastManager.getInstance(MainActivity.this)
                            .sendBroadcast(intent);
                }
            });
        }
    }
  • 相关阅读:
    sql语句查询数据库中含有某字符串的表名
    PHP复制文件夹及文件夹内的文件
    Vue.js绑定内联样式
    Vue模板语法V-bind
    Vue实例
    Vue.js几个简单用法
    Git Pull Failed: cannot lock ref 'refs/remotes/origin/xxxxxxxx': unable to resolve ref
    SSM 框架详细整合教程(IDEA版)(Spring+SpringMVC+MyBatis)
    IntelliJ IDEA(2017/2018)安装图解与破解教程
    Hadoop集群单机伪分布搭建
  • 原文地址:https://www.cnblogs.com/qitian1/p/6461797.html
Copyright © 2011-2022 走看看