Thursday, December 19, 2013

Broadcast receivers example: Android tutorial

Program description:

This is a demo program on how to create a broadcast receiver and how to send a broadcast message.


Broadcast receiver: it is a component of android which responds to system wide broadcast announcements.

If any important even occurs in phone like battery low, new incoming sms, incoming call, file download etc.. then system will take that event and send it as a broadcast message to all the applications in the phone. If any application is interested in responding to that event, then that application has to register a broadcast receiver for that intent.

This application has an activity and a broadcast receiver. Activity contains a button. On clicking the button we will send a broadcast message to our receiver using explicit intent.
If you want to trigger a receiver by using implicit intent, then you can follow my tutorial on how to use implicit intent.

We use sendBroadcast() function to send a broad cast message. 
Every broadcast receiver extends from class BroadcastReceiver.
To create a broadcast receiver, go to manifest file -> application tab -> scroll down -> click add button -> select receiver and give a name for your receiver. That's it, it creates a java file which contains your broadcast receiver code.

android interview questions on broadcast receivers

First activity

package com.techpalle.b15_broadcastreceivers;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
 Button b;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  b = (Button) findViewById(R.id.button1);
  b.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent in = new Intent(getApplicationContext(), 
      MyReceiver.class);
    sendBroadcast(in);
   }
  });
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}

xml file for first activity 
File name : activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   tools:context=".MainActivity" >  
   <TextView  
     android:id="@+id/textView1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="@string/hello_world" />  
   <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignLeft="@+id/textView1"  
     android:layout_below="@+id/textView1"  
     android:text="Send Broadcast" />  
 </RelativeLayout>  

Broadcast receiver
File name : MyReceiver.java

package com.techpalle.b15_broadcastreceivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
   /*Broadcast receiver has maximum time limit of 10 seconds
    *so.. don't do heavy functionalities in receiver.*/
   /*1. don't show dialogs
   * 2. don't do long running operations (sd card, db, internet)
   * 3. don't bind to services 
   */
  Toast.makeText(context, "Reciever triggered..", 0).show();
 }
}

Manifest file
File name : AndroidManifest.xml


 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.techpalle.b15_broadcastreceivers"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   <uses-sdk  
     android:minSdkVersion="8"  
     android:targetSdkVersion="17" />  
   <application  
     android:allowBackup="true"  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name"  
     android:theme="@style/AppTheme" >  
     <activity  
       android:name="com.techpalle.b15_broadcastreceivers.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="MyReceiver"></receiver>  
   </application>  
 </manifest>  

Download complete code : Click to download

Interview questions on broadcast receivers:
Difference between service and broadcast receiver?
How to start an application on phone boot complete?
What is the time limit of a broadcast receiver?
How to notify user from a broadcast receiver?

Tags: android, broadcast receiver, sendbroadcast

android broadcast receiver interview questions and answers

17 comments:

  1. After reading your post I understood that last week was with full of surprises and happiness for you. Congratz! Even though the website is work related, you can update small events in your life and share your happiness with us too.
    Click here:
    angularjs training in bangalore
    Click here:
    angularjs training in chennai

    ReplyDelete
  2. I really like the dear information you offer in your articles. I’m able to bookmark your site and show the kids check out up here generally. Im fairly positive theyre likely to be informed a great deal of new stuff here than anyone
    Click here:
    Microsoft azure training in sollinganallur
    Click here:
    Microsoft azure training in btm

    ReplyDelete
  3. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Devops training in sholinganallur

    ReplyDelete
  4. This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.
    java training in annanagar | java training in chennai

    java training in chennai | java training in electronic city

    ReplyDelete
  5. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
    angularjs online training

    apache spark online training

    informatica mdm online training

    devops online training

    aws online training

    ReplyDelete
  6. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    blue prism Training in Electronic City

    ReplyDelete
  7. I am really happy to see your blog..
    BEST ANGULAR JS TRAINING IN CHENNAI WITH PLACEMENT

    https://www.acte.in/angular-js-training-in-chennai
    https://www.acte.in/angular-js-training-in-annanagar
    https://www.acte.in/angular-js-training-in-omr
    https://www.acte.in/angular-js-training-in-porur
    https://www.acte.in/angular-js-training-in-tambaram
    https://www.acte.in/angular-js-training-in-velachery

    ReplyDelete
  8. A befuddling web diary I visit this blog, it's incredibly grand. Strangely, in this present blog's substance made motivation behind fact and sensible. The substance of information is instructive
    Angular js Training in Chennai

    Angular js Training in Velachery

    Angular js Training in Tambaram

    Angular js Training in Porur

    Angular js Training in Omr

    Angular js Training in Annanagar

    ReplyDelete
  9. Thank you so much for sharing these amazing tips. I must say you are an incredible writer, I love the way that you describe the things. Please keep sharing.
    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    Spoken english classes in chennai | Communication training

    ReplyDelete