使用Broadcast实现Android组件间的通信
更新时间:2016年06月08日 11:15:05 作者:_江南一点雨
这篇文章主要为大家详细介绍了使用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);
}
});
}
}
原文链接:http://blog.csdn.net/u012702547/article/details/46816331
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Android实现界面内嵌多种卡片视图(ViewPager、RadioGroup)
这篇文章主要为大家详细介绍了Android实现界面内嵌多种卡片视图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-09-09
Android RecyclerView添加FootView和HeadView
这篇文章主要介绍了Android RecyclerView添加FootView和HeadView的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2016-10-10
Android ListView中动态添加RaidoButton的实例详解
这篇文章主要介绍了Android ListView中动态添加RaidoButton的实例详解的相关资料,需要的朋友可以参考下2017-08-08
Eclipse NDK迁移到Android Studio的方法示例
本篇文章主要介绍了Eclipse NDK迁移到Android Studio的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-03-03


最新评论