设为首页 加入收藏

TOP

使用Broadcast实现Android组件之间的通信
2015-07-20 12:52:45 来源: 作者: 【 】 浏览:33
Tags:使用 Broadcast 实现 Android 组件 之间 通信

效果如图:



布局文件:


? ? xmlns:tools="http://schemas.android.com/tools"
? ? android:layout_width="match_parent"
? ? android:layout_height="match_parent"
? ? android:orientation="vertical" >


? ? ? ? ? ? android:id="@+id/textView1"
? ? ? ? android:layout_width="wrap_content"
? ? ? ? android:layout_height="wrap_content"
? ? ? ? android:text="@string/hello_world" />


? ? ? ? ? ? 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="发送广播" />



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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇设计模式在项目中的应用 下一篇10行Java代码实现最近被使用(LRU..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: