1. 建立Receiver,兩種方式,動態和靜態:
(1)靜態註冊:
首先自訂個Receiver,
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "MyReceiver broadcast", 10000).show();
}
}
然後在AndroidManifest註冊即可:
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.test.broadcasting" />
</intent-filter>
</receiver>
(2)動態註冊:
private void regReceiver() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.test.broadcasting");
// 註冊BroadcastReceiver
this.registerReceiver(receiver, intentFilter);
// 取消註冊
// this.unregisterReceiver(receiver);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "receive broadcast", 10000).show();
}
};
2.發送廣播:
這個非常簡單,只需一行代碼即可:
this.sendBroadcast(new Intent("com.test.broadcasting"));
3. 應用情境:
最常見的就是SD插拔的廣播註冊(android.content.Intent.ACTION_MEDIA_MOUNTED).