標籤: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); } }); }}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
使用Broadcast實現android組件之間的通訊