Android tip #020 – Broadcast intents
Platform/Language: Java/Android
Description: we can send broadcast messages (Intents) in our application. They can be useful when we need to comunicate Activities with other Activities, Services with Activities and so on. It is a good way to send and listen messages in the whole application.
We need a receiver (which will listen the message) and a sender (which will send the message)
Code:
Sender.java
1 2 3 4 5 6 7 | public static final String BROADCAST_MESSAGE = "my_message"; private void sendBroadcastMessage(Context context) { Intent i = new Intent(); i.setAction(BROADCAST_MESSAGE); context.sendBroadcast(i); } |
ReceiverActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class ReceiverActivity extends Activity { private BroadcastReceiver receiver = new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { ReceiverActivity.this.doSomething(); } }; private void doSomething() { } public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(Sender.BROADCAST_MESSAGE); this.registerReceiver(this.receiver, filter); } public void onPause() { super.onPause(); this.unregisterReceiver(this.receiver); } /* ... */ } |

