BroadcastReceiver and Intents

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

BroadcastReceiver and Intents

Postby MyFriendMathis2 » Sat Jan 29, 2011 10:04 pm

BroadcastReceiver and Intents

The purpose of this tutorial is to help you to create a broadcast receiver and see how you can interact with the system events, in the simpliest way with no blabla.

What is a BroadcastReceiver ?

It is just a class with an onReceive() method which will be triggered when the system sent that something has happened like an incoming sms or a low battery power.

For example if you want to do something when an ac power is plug to your phone, create your own class :
Code: Select all
public class BroadCastTest extends BroadcastReceiver
{

   @Override
   public void onReceive(Context context, Intent intent)
   {
      // TODO Auto-generated method stub
   
   }

}


What does mean context and intent ? Don’t panic..
First, what you have to know, is that, usually, you don’t have to instantiate the receiver class yourself. Android can do that for you.
Just declare it in your manifest.xml by doing this :
Code: Select all
        <receiver android:name=".BroadCastTest"/>
                <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
               </intent-filter>
         </receiver>


This xml code tells to Android that your class exists and can be instantiated automatically if it is concerned by an event.

You notice the intent filter section, which is not easy to understand on the Android website.
Let say it is just a semaphore or a flag which tells : i am a broadcastreceiver for the action called ACTION_POWER_CONNECTED (means when ac power is connected please trigger me).
So, suppose you connect your phone to ac adapter -> Android generates an event, «a broadcast event», instantiate your class and calls onReceive method.

You can add filters to be concerned by other events:
Code: Select all
       <receiver android:name=".BroadCastTest"/>
                <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />   
               </intent-filter>
         </receiver>


In this case, your broadcast will also be instantiated and triggered when an sms is received. Don't forget to add permission to receive sms in your manifest:
Code: Select all
<uses-permission android:name="android.permission.RECEIVE_SMS" />

You will find the different actions possibles in the intent class documents on the android website.
MyFriendMathis2
Once Poster
Once Poster
 
Posts: 1
Joined: Sat Jan 29, 2011 8:29 pm

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 6 guests