菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
147
0

使用Broadcast实现android组件之间的通信 分类: android 学习笔记 2015-07-09 14:16 110人阅读 评论(0) 收藏

原创
05/13 14:22
阅读数 69477

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);
            }
        });
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

发表评论

0/200
147 点赞
0 评论
收藏