在Android中,Broadcast是一種廣泛運用的在應用程序之間傳輸信息的機制。而BroadcastReceiver是對發送出來的 Broadcast進行過濾接受並響應的一類組件。
下面將詳細的闡述如何發送Broadcast和使用BroadcastReceiver過濾接收的過程:
首先在需要發送信息的地方,把要發送的信息和用於過濾的信息(如Action、Category)裝入一個Intent對象,然后通過調用 sendOrderBroadcast()或sendStickyBroadcast()方法,把 Intent對象以廣播方式發送出去。
當Intent發送以后,所有已經注冊的BroadcastReceiver會檢查注冊時的IntentFilter是否與發送的Intent相匹配,若匹配則就會調用BroadcastReceiver的onReceive()方法。所以當我們定義一個BroadcastReceiver的時候,都需要實現onReceive()方法。
注冊BroadcastReceiver有兩種方式:
靜態注冊:在AndroidManifest.xml中用標簽生命注冊,並在標簽內用標簽設置過濾器。
<receiver android:name="myRecevice"> //繼承BroadcastReceiver,重寫onReceiver方法
<intent-filter>
<action android:name="com.dragon.net"></action> //使用過濾器,接收指定action廣播
</intent-filter>
</receiver>
動態注冊:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(String); //為BroadcastReceiver指定action,使之用於接收同action的廣播
registerReceiver(BroadcastReceiver,intentFilter);
一般:在onStart中注冊,onStop中取消unregisterReceiver
指定廣播目標Action:Intent intent = new Intent(actionString);
並且可通過Intent攜帶消息 :intent.putExtra("msg", "hi,我通過廣播發送消息了");
發送廣播消息:Context.sendBroadcast(intent )
其中在動態注冊中可將BroadcastReceiver的繼承類進行封裝,添加構造函數和BroadcastReceiver注冊
代碼 import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; public class BroadcastReceiverHelper extends BroadcastReceiver { NotificationManager mn=null; Notification notification=null; Context ct=null; BroadcastReceiverHelper receiver; public BroadcastReceiverHelper(Context c){ ct=c; receiver=this; } //注冊 public void registerAction(String action){ IntentFilter filter=new IntentFilter(); filter.addAction(action); ct.registerReceiver(receiver, filter); } @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String msg=intent.getStringExtra("msg"); int id=intent.getIntExtra("who", 0); if(intent.getAction().equals("com.cbin.sendMsg")){ mn=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notification=new Notification(R.drawable.icon, id+"發送廣播", System.currentTimeMillis()); Intent it = new Intent(context,Main.class); PendingIntent contentIntent=PendingIntent.getActivity(context, 0, it, 0); notification.setLatestEventInfo(context, "msg", msg, contentIntent); mn.notify(0, notification); } } }
然后再Activity中聲明BroadcastReceiver的擴展對象,在onStart中注冊,onStop中卸載:
BroadcastReceiverHelper rhelper; @Override public void onStart(){ //注冊廣播接收器 rhelper=new BroadcastReceiverHelper(this); rhelper.registerAction("com.cbin.sendMsg"); super.onStart(); } @Override public void onStop(){ //取消廣播接收器 unregisterReceiver(rhelper); super.onStop(); }