2016年3月2日 星期三

send Broadcast and Broadcast Receiver

Broadcast Receiver

1.create a class extends Brodcast Receiver

2. override onReceive
this method will run after the Receiver receive the brodcast

 private class MyBrodcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
//do something
        }
    }

3 register the Broadcast Receiver
only registered Broadcast Receiver can receiver brodcast,what message ,depend on the intern filter

M1.register in the program


//register the brodcast receiver
                MyBrodcastReceiver mybrodcastReceiver=new MyBrodcastReceiver();
                IntentFilter intentFilter=new IntentFilter(BRODCAST_ACTION);
                getActivity().registerReceiver(mybrodcastReceiver,intentFilter);


M2.register in XML

 <receiver android:name=".AddBook$MyBrodcastReceiver">
            <intent-filter>
                <action android:name="it.jaschke.alexandria.brodcastmessage"/>
            </intent-filter>
        </receiver>



4.send Brodcast

Intent brodcastIntent=new Intent();
    brodcastIntent.setAction(AddBook.BRODCAST_ACTION);
    sendBroadcast(brodcastIntent);

the action should be match to the InterFilter.