Broadcast实现Android组件间的通信 使用Broadcast实现Android组件间的通信

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Broadcast实现Android组件间的通信 使用Broadcast实现Android组件间的通信

_江南一点雨   2021-03-22 我要评论
想了解使用Broadcast实现Android组件间的通信的相关内容吗,_江南一点雨在本文为您仔细讲解Broadcast实现Android组件间的通信的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,组件,Broadcast,通信,下面大家一起来学习吧。

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

原文链接:http://blog.csdn.net/u012702547/article/details/46816331

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们