LocalBroadcastManager
雖然android 有一個方便使用的broadcast機制,
但因為一般的broadcast是全域系統的廣播, 常常會佔住系統不少資源
而LocalBroadcastManager是屬於app process內的broadcast,
比較不會干擾到其他process或受到其他process的影響
使用方式如下:
//先宣告要收甚麼類型的intent
@Override
public void onCreate(Bundle savedInstanceState) {
...
IntentFilter ifilter = new IntentFilter("my.local.intent")
LocalBroadcastManager.getInstance(this).registerReceiver(mMyReceiver, ifilter );
...
//發送local broadcast
Intent intent = new Intent("my.local.intent");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private BroadcastReceiver mMyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("MYReceiver", "Got intent:" + intent);
}
};
@Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMyReceiver);
}