【正文】
a d c a s t R e c e i v e r 基 類 BroadcastReceiver介紹 ? 廣播是一種廣泛運(yùn)用在應(yīng)用程序之間傳輸信息的機(jī)制,而 BroadcastReceiver是對發(fā)送出來的廣播進(jìn)行過濾接收并響應(yīng)的一類組件。通常一個(gè)廣播可以被訂閱了該 Intent的多個(gè)廣播接收者所接收,如同一個(gè)廣播臺,可以被多位聽眾收聽一樣。 BroadcastReceiver介紹 開發(fā)自己的 BroadcastReceiver與開發(fā)其他組件一樣,只需要繼承 Android中的 BroadcastReceiver基類 ,然后 實(shí)現(xiàn)里面的相關(guān)方法 即可。 receiver android:name=.MyBroadcastReceiver intentfilter action android:name= /action /intentfilter /receiver 靜態(tài)注冊: 是指在 。 動態(tài) 注冊: 需要在代碼中 動態(tài)的指定廣播地址并注冊 ,通常是在 Activity或 Service中調(diào)用 ContextWrapper的registerReceiver( BroadcastReceiver receiver,IntentFilter filter)方法進(jìn)行 注冊 。所以不要在廣播接收者的 onReceive()方法里執(zhí)行一些耗時(shí)的操作,否則會彈出 ANR( Application No Response)對話框。這樣就可能導(dǎo)致BroadcastReceiver啟動的 子線程不能執(zhí)行完成 。但缺點(diǎn)是接收者不能將處理結(jié)果傳遞給下一個(gè)接收者,并且無法終止 Broadcast Intent的傳播。 發(fā)送有序廣播示例 public class ABroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { (context, “ A is Invoked!” , ).show()。 setContentView()。 setContentView()。 (context, “ B is Invoked!” +“得到的信息” +(“ A” ), ).show()。//在廣播中添加數(shù)據(jù) setResultExtras(bundle)。 ? 此程序中包含兩個(gè) BroadcastReceiver(廣播接收器)和一個(gè) Service服務(wù) 。 setContentView()。 author = (TextView) findViewById()。//為播放和停止按鈕添加事件監(jiān)聽 activityReceiver = new ActivityReceiver()。//顯 式 調(diào)用服務(wù) startService(intent)。//獲取當(dāng)前播放的音樂的序號 if (current = 0) { (titles[current])。 case 0x12://處于播放狀態(tài),則顯示暫停按鈕 ()。 default: break。//傳遞值為 1 break。 } sendBroadcast(intent)。//創(chuàng)建廣播接收器 IntentFilter intentFilter = new IntentFilter( )。 音樂播放器示例 public class ServiceReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { int control = (control, 1)。 status=0x13。 case 2://如果單擊的是停止 if(status==0x12||status==0x13){//如果處于播放或暫停狀態(tài) ()。 } Intent sendIntent=new Intent()。//發(fā)送廣播 } } Service中的廣播接收器,用于控制音樂的播放、暫停以及停止。 } Intent sendIntent=new Intent()。//準(zhǔn)備和播放當(dāng)前歌曲 } })。//播放音樂 }catch(Exception ex){ ()。 處 理 完后 , 該 S e r v i c e R e c e i v e r 會 發(fā) 送 一 條 廣 播 , 該 廣 播 能 被 A c t i v i t y 中 的A c t i v i t y R e c e i v e r 接 收 到 , 并 進(jìn) 行 相 應(yīng) 處 理 , 主 要 是 在 播 放 和 暫 停 兩 個(gè) 按 鈕 圖片 間 進(jìn) 行 切 換