對于了解Android程序設(shè)計的人都知道,廣播是Android開發(fā)中的一個重要的功能,在Android里面有各式各樣的廣播,比如:電池的狀態(tài)變化、信號的強弱狀態(tài)、電話的接聽和短信的接收等等,今天本文就來給大家簡單介紹一下系統(tǒng)發(fā)送、監(jiān)聽這些廣播的機(jī)制。
Android中的廣播機(jī)制基本如下圖所示:

那廣播在Android程序中到底是如何運行的呢?下面將以代碼的形式給大家好好分析一下:
一、發(fā)送廣播
Intent是Activity中發(fā)送廣播的橋梁,通過他我們可以輕松的將廣播發(fā)送到系統(tǒng)中,具體的實現(xiàn)如下:
final String Intent_Action = "com.android.BroadcastReceiverDemo";//定義廣播,方便我們接收這個廣播Intent intent = new Intent(Intent_Action);intent.putExtra("name", "小米");Activityone.this.sendBroadcast(intent); 可能你會疑惑Intent_Action的用處,因為Android內(nèi)部存在大量的廣播,我們通過Intent_Action可以唯一的接收這條廣播。
二、接收廣播
接收廣播時我們需要定義一個BroadcastReceiver的子類,來接收我們發(fā)出的廣播,通過重寫B(tài)roadcastReceiver的onReceive()方法來對接到的廣播做出響應(yīng)。
public class MyBroadcastReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stub String name = intent.getStringExtra("name");//獲得廣播發(fā)出者傳遞的值 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",高亮的內(nèi)容和我們在發(fā)送廣播時設(shè)置Intent_Action的內(nèi)容一致。
希望本文示例對大家的Android程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選