Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 廣播機制淺析:發送、接收與配置

編輯:Android 開發實例

熟悉 Android 程式設計的人都知道,廣播是 Android 開發中一項重要的功能。Android 裡有各式各樣的廣播,例如:電池狀態變化、訊號強弱、電話接聽、簡訊接收等等。今天本文就來為大家簡單介紹系統是如何發送與監聽這些廣播的。

Android 中的廣播機制大致如下圖所示:

那麼廣播在 Android 程式中究竟是如何運作的呢?下面將以程式碼的形式為大家逐一剖析:

一、發送廣播

Intent 是 Activity 中發送廣播的橋樑,透過它可以輕鬆地將廣播送入系統,具體實現如下:

 final String Intent_Action = "com.android.BroadcastReceiverDemo";//定義廣播,方便我們接收這個廣播 Intent intent = new Intent(Intent_Action); intent.putExtra("name", "小米"); Activityone.this.sendBroadcast(intent); 

你可能會好奇 Intent_Action 的用途——由於 Android 內部存在大量廣播,透過 Intent_Action 我們才能唯一地接收到這條廣播。

二、接收廣播

要接收廣播,我們需要定義一個 BroadcastReceiver 的子類別來接收自己發出的廣播,並透過重寫 BroadcastReceiver 的 onReceive() 方法,對收到的廣播做出響應。

 public class MyBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String name = intent.getStringExtra("name");//獲得廣播發出者傳遞的值 Toast.makeText(context, name, Toast.LENGTH_SHORT).show(); } 

三、配置廣播

設定檔部分的程式碼如下:

 <receiver android:name="cn.edu.hpu.android.activity_broadcast.MyBroadcastReceiver" android:enabled="true" > <intent-filter > <action android:name="com.android.BroadcastReceiverDemo" /> </intent-filter> </receiver> 

這裡一定要確保 android:name="com.android.BroadcastReceiverDemo" 中反白的內容,與我們發送廣播時設定的 Intent_Action 內容一致。

希望本文的示例能對大家的 Android 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved