Smartphones

An Android coder's introduction to broadcast receivers

Android's version of a party line is its BroadcastReceiver class. This demo shows how to create, register, and use a broadcast receiver to listen for device orientation changes.

When I was a kid, we lived out in the sticks, and our phone service was what was known as a party line. I suspect some of you reading this blog have no idea what a party line is, so both to educate and date myself let me quickly explain. A party line was a phone line that you shared with one or more of your neighbors.

In our case, we shared a phone line with Mrs. Stump, the elderly woman who owned an apple orchard across the street. When you wanted to make a call, you picked up the receiver, but before dialing (on a real honest to goodness rotary dial), you had to first listen and see if Mrs. Stump was already on the phone. If she was, the polite thing to do was hang up. (Mrs. Stump seemed ancient to me back then, but she had very sharp hearing and I assure you if you did not do the polite thing later that day Mrs. Stump would have a chat with your mother.)

What does any of this have to do with Android development? Well, the Android operating system has an internal mechanism called a broadcast/receiver model that works a bit like the old party phone lines. The operating system and even other applications periodically broadcast messages about things that are happening, such as the battery status changed, the Wi-Fi came on, or the phone's orientation changed. These are all things that are being announced in real time, and if you know how to pick up the phone and listen, your code can react accordingly without the overhead of unnecessarily polling for the state that interests you.

You can read Google's official explanation of a BroadcastReceiver. If like me though you prefer a code sample, I've created a short demonstration of how to create, register, and utilize a broadcast receiver to listen for device orientation changes. You can follow along with the tutorial, or download the entire project and import it into your workspace directly.

1. Create a new Android project in Eclipse. Target the SDK for Android 1.6 or greater. Be sure to change the startup file to Main.java.

2. In our /res/layout folder we will want to define the layout for our Main.java file. Open main.xml and add a couple of text views.

main.xml
<?xml version=<em>"1.0"</em> encoding=<em>"utf-8"</em>?>
<p><LinearLayout xmlns:android=<em><a href="http://schemas.android.com/apk/res/android">http://schemas.android.com/apk/res/android</a></p>
<p></em> android:layout_width=<em>"fill_parent"</p>
<p></em> android:layout_height=<em>"fill_parent"</p>
<p></em> android:orientation=<em>"vertical"</em> ></p>
<p><TextView</p>
<p>android:layout_width=<em>"fill_parent"</p>
<p></em> android:layout_height=<em>"wrap_content"</p>
<p></em> android:textColor=<em>"#00ff00"</p>
<p></em> android:textSize=<em>"20dip"</p>
</em> <span style="text-decoration: underline;">android:text=<em>"Broadcast Receiver Demo"</em></span> />
<p><TextView</p>
<p>android:layout_width=<em>"fill_parent"</p>
<p></em> android:layout_height=<em>"wrap_content"</p>
</em> <span style="text-decoration: underline;">android:text=<em>"(rotate the phone to activate receiver)"</em></span> />
</LinearLayout>

3. Let's take a look at the Main.java file in our /src folder. To start with, we will want to declare a new broadcast receiver. I've done this inline, though if you don't prefer Java's inline syntax, you can always extend BroadcastReceiver with your own custom class.

Main.java
<strong>package</strong> com.authorwjf.broadcast_receiver;
<strong>import</strong> android.app.Activity;
<strong>import</strong> android.content.BroadcastReceiver;
<strong>import</strong> android.content.Context;
<strong>import</strong> android.content.Intent;
<strong>import</strong> android.content.IntentFilter;
<strong>import</strong> android.content.res.Configuration;
<strong>import</strong> android.os.Bundle;
<strong>import</strong> android.widget.Toast;
<strong>public</strong> <strong>class</strong> Main <strong>extends</strong> Activity {
<strong>private</strong> BroadcastReceiver the_receiver = <strong>new</strong> BroadcastReceiver(){
@Override
<strong>public</strong> <strong>void</strong> onReceive(Context c, Intent i) {
<strong>int</strong> orientation = getBaseContext().getResources().getConfiguration().orientation;
<strong>if</strong> (orientation == Configuration.<em>ORIENTATION_PORTRAIT</em>) {
<p>Toast.<em>makeText</em>(getBaseContext(), "I'm still standing.", Toast.<em>LENGTH_SHORT</em>).show();</p>
} <strong>else</strong> <strong>if</strong> (orientation == Configuration.<em>ORIENTATION_LANDSCAPE</em>) {
<p>Toast.<em>makeText</em>(getBaseContext(), "Help! I've fallen and I can't get up.", Toast.<em>LENGTH_SHORT</em>).show();</p>
} <strong>else</strong> {
<p>Toast.<em>makeText</em>(getBaseContext(), "?!#$%!?", Toast.<em>LENGTH_SHORT</em>).show();</p>
<p>}</p>
<p>}</p>
};
<strong>private</strong> IntentFilter filter = <strong>new</strong> IntentFilter(Intent.<em>ACTION_CONFIGURATION_CHANGED</em>);
}

4. With the receiver defined and a couple actions in place for handling a receive, what's left is to handle the registering and unregistering of the receiver. It's possible to register your broadcast receiver in the Android manifest for the activity; you can find an example of doing this on the Google's official documentation site. I prefer to register my broadcast receivers in code, largely because it gives me the ability to dynamically connect and disconnect them as I choose.

Main.java
<p>@Override</p>
<strong>public</strong> <strong>void</strong> onCreate(Bundle savedInstanceState) {
<strong>super</strong>.onCreate(savedInstanceState);
<p>setContentView(R.layout.<em>main</em>);</p>
}
@Override
<strong>protected</strong> <strong>void</strong> onResume() {
<strong>this</strong>.registerReceiver(the_receiver, filter);
<strong>super</strong>.onResume();
}
@Override
<strong>protected</strong> <strong>void</strong> onPause() {
<strong>this</strong>.unregisterReceiver(the_receiver);
<strong>super</strong>.onPause();
}

5. Open the manifest and enable orientation change detection by adding the following option to the activity:

android:configChanges="orientation"

That does it. Load the code to your device or Emulator and then rotate your phone (Ctrl F12 on the emulator). When the broadcast is received, the receiver displays an appropriate toast message (Figure A).

Figure A

See, it's Android's version of a party line. I find broadcast receivers simple and extremely useful. Just remember to "hang up" when you are done listening using the unregister receiver call; otherwise, Google might send someone over to chat with your mother!

About

William J Francis began programming computers at age eleven. Specializing in embedded and mobile platforms, he has more than 20 years of professional software engineering under his belt, including a four year stint in the US Army's Military Intellige...

2 comments
Rahul Rana
Rahul Rana

hi I want to get the broadcast receiver when any activity open on android device/emulator, I am beginner in android so please help me................... Thanx in advance.

kaushalkomawar
kaushalkomawar

Hi i have downloaded the code u provided . its running but not showing the messages when screen gets rotated. i m using eclipse and emulator for running the app. pls help me out