Broadcast Receiver in Android

August 07, 2013
Broadcast Receiver:
A Broadcast Receiver is a component that responds to system-wide broadcast announcements.

Examples: 
1.Screen has turned off.
2.Battery is getting low.

3.A picture was captured...etc.

Implementation:
A broadcast receiver extends with BroadcastReceiver class and which is registered as a receiver in an android application via the AndroidManifest.xml file.

Alternatively ,we can also register broadcast receiver dynamically via the Context.registerReceiver() method.


In an event for which the broadcast receiver happens the onReceive() method of the broadcast receiver is called.

Usage:
package com.ram.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        
    }

}

 Registering in AndroidManifest file
AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.broadcastreceiver"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.broadcastreceiver.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="MyBroadcastReceiver">
      <intent-filter ></intent-filter>
       </receiver>
    </application>
</manifest>





Artikel Terkait

Previous
Next Post »