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