Friday, 15 May 2015

Broadcast Receiver Example

  1. What is Broadcast receiver in android:-
    Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. 

    There are following two important steps to make Broadcast Receiver works for the system broadcast intents:

  2. Creating the Broadcast Receiver.
  3. Registering Broadcast Receiver.

    • Creating the Broadcast Receiver:-

      A broadcast receiver is implemented as a subclass of Broadcast Receiver class and overriding the onReceive() method where each message is received as a Intent object parameter.


      public class MyReceiver extends BroadcastReceiver {

         @Override
         public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Intent Detected.",  Toast.LENGTH_LONG).show();
         }

      }




      Registering Broadcast Receiver

      An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process.

      <application
         android:icon="@drawable/ic_launcher"
         android:label="@string/app_name"
         android:theme="@style/AppTheme" >

         <receiver android:name="MyReceiver">
            <intent-filter>
               <action android:name="android.intent.action.BOOT_COMPLETED">
            </action>
            </intent-filter>
         </receiver>

      </application>

      Types of Broadcast receiver in android:-

      1. android.intent.action.BATTERY_CHANGED
      2. android.intent.action.BATTERY_LOW
      3. android.intent.action.BATTERY_OKAY
      4. android.intent.action.BOOT_COMPLETED
      5. android.intent.action.BUG_REPORT
      6. android.intent.action.CALL
      7. android.intent.action.CALL_BUTTON
      8. android.intent.action.DATE_CHANGED
      9. android.intent.action.REBOOT