Monday, May 23, 2011

broadcast receiver with example

broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcasts—for example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event.
A broadcast receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent object. For more information, see the BroadcastReceiver class.


We will define a broadcast receiver which listens to telephone state changes. If the phone receives a phone call then our receiver will be notified and log a message.
Create a new project "de.vogella.android.receiver.phone". We do not need an activity. Create the following "AndroidManifest.xml".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="de.vogella.android.receiver.phone" android:versionCode="1"
 android:versionName="1.0">
 <application android:icon="@drawable/icon" android:label="@string/app_name">


  <receiver android:name="MyPhoneReceiver">
   <intent-filter>
    <action android:name="android.intent.action.PHONE_STATE"></action>
   </intent-filter>
  </receiver>
 </application>
 <uses-sdk android:minSdkVersion="9" />


 <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
</manifest> 
  
Create the following class "MyPhoneReceiver".
package de.vogella.android.receiver.phone;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class MyPhoneReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  Bundle extras = intent.getExtras();
  if (extras != null) {
   String state = extras.getString(TelephonyManager.EXTRA_STATE);
   Log.w("DEBUG", state);
   if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
    String phoneNumber = extras
      .getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
    Log.w("DEBUG", phoneNumber);
   }
  }
 }
}

 

No comments:

Post a Comment