iis服务器助手广告广告
返回顶部
首页 > 资讯 > 移动开发 >使用Broadcast实现Android组件间的通信
  • 177
分享到

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

通信Android 2022-06-06 08:06:49 177人浏览 独家记忆
摘要

Android组件之间的通信有多种实现方式,Broadcast就是其中一种。在activity和fragment之间的通信,broadcast用的更多本文以一个activity

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

您可能感兴趣的文章:Android之网络通信案例分析Android Handler主线程和一般线程通信的应用分析深入理解Android组件间通信机制对面向对象特性的影响详解Android组件间通信--深入理解Intent与IntentFilterAndroid 进程间通信实现原理分析android 网络编程之网络通信几种方式实例分享Android中Socket通信的实现方法概述Android提高之Android手机与BLE终端通信python服务器与android客户端socket通信实例浅析Android系统中https通信的实现


--结束END--

本文标题: 使用Broadcast实现Android组件间的通信

本文链接: https://www.lsjlt.com/news/24855.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作