Recipe 1.4 Sending and Receiving Broadcasts

Android Versions
Level 1 and above
Permissions
None
Source Code to Download at Wrox.com
UsingBroadcastReceiver.zip

In Android, a broadcast enables you to send a message to another part of your application (or another application) so that you can inform it of something happening. In this recipe, you learn how to create a broadcast receiver to listen for broadcasts, as well as send broadcasts to other applications.

Solution

There are two ways to create a broadcast receiver: programmatically through code and declaratively via the AndroidManifest.xml file. The following sections address each possible solution.

Programmatically Registering a Broadcast Receiver

Consider the following activity:

package net.learn2develop.usingbroadcastreceiver;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    MyBroadcastReceiver myReceiver;
    IntentFilter intentFilter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myReceiver = new MyBroadcastReceiver();
        intentFilter = new IntentFilter("MY_SPECIFIC_ACTION");
    }
    @Override
    public void onResume() {
        super.onResume();
        //---register the receiver---
 registerReceiver(myReceiver, ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.