Thursday, December 26, 2013

Dynamic broadcast receivers: Android tutorial

Program description:

This is a sample demo program for dynamic broadcast receivers in Android.

This program contains only one activity, which has a dynamic broadcast receiver in it.
Activity has 2 buttons. On clicking one button we will register the dynamic receiver. On clicking other button we will send a broadcast message which triggers our dynamic receiver.

There are 2 ways to create a broadcast receiver in android:
1. Static way of creating broadcast receiver: Generally we create broadcast receivers in manifest file with a receiver tag. This is static way.
     Check How to create Broadcast receivers statically
2. Dynamic receiver: The receiver created directly using android code with out any tag in the manifest file.

What is the use of dynamic broadcast receivers?
If some one sends a broadcast with some intent, and if our broadcast receiver's intent-filter filter matches with it, then android will start our receiver. (Even if our application is not running currently).
But we may not want this in some situations. 
Example: I want my receiver to be triggered when battery goes down, and if user is playing with my game. In this situation if we create receiver by static way (in manifest file), then if battery goes down, then android will start our receiver irrespective of whether user is playing with our game or not. But that is not what we need. We need our receiver to get executed only if our application is currently running (in the memory).
Solution for this is dynamic broadcast receivers.

Properties of dynamic receivers:
1. They will get executed only if the application which has registered it, is in the memory and running currently.
2. It will not get executed if the application is not currently running.
3. We will not create it by using manifest file, rather by using android code.

Note: To get it worked properly, we have to register the receiver properly. Once work is done, make sure that you are unregistering the receiver.

First Activity:


package com.techpalle.b15_dynrec;

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

public class MainActivity extends Activity {

 private BroadcastReceiver br = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
   // TODO Auto-generated method stub
   Toast.makeText(context, "dyn got it..", 0).show();
  }
 };
 Button b1, b2;
 private IntentFilter inf;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  b1 = (Button) findViewById(R.id.button1);
  b2 = (Button) findViewById(R.id.button2);
  
  inf = new IntentFilter();
  inf.addAction("com.techpalle.action.DYN_REC");

  b1.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent in = new Intent();
    in.setAction("com.techpalle.action.DYN_REC");
    sendBroadcast(in);
   }
  });
  b2.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    registerReceiver(br, inf);
   }
  });
 }

 @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;
 }
 @Override
 protected void onStop() {
  // TODO Auto-generated method stub
  unregisterReceiver(br);
  super.onStop();
 }
}

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:layout_marginLeft="35dp"  
     android:layout_marginTop="64dp"  
     android:text="Send Broadcast" />  
   <Button  
     android:id="@+id/button2"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignRight="@+id/button1"  
     android:layout_below="@+id/button1"  
     android:layout_marginTop="56dp"  
     android:text="Register Receiver" />  
 </RelativeLayout>  

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_dynrec"  
   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_dynrec.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>  
   </application>  
 </manifest>  

Download complete code : Click to download

Android interview questions on dynamic broadcast receivers:
How to create broadcast receiver with out using manifest file?
How to start a receiver only if the application is running?

Tags: android, dynamic receivers, register receiver, button click

Advertisement:
Own your smart phone at exciting low prices


4 comments:

  1. Gambling: What it is & How To Know - Dr.MD
    › gambling › gambling › gambling › gambling › gambling › gambling › 구리 출장샵 gambling › gambling › gambling · gambling · gambling 경주 출장마사지 · gambling 서울특별 출장안마 · gambling · 이천 출장안마 gambling · gambling 강릉 출장안마 · gambling · gambling.

    ReplyDelete