Thursday, December 26, 2013

Sticky broadcast receivers: android tutorial

Program description:

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


Our program has only one activity, which contains a dynamic broadcast receiver in that activity.
Activity has 2 buttons. On clicking one button we will register dynamic receiver with action com.techpalle.STICK. On clicking other button we will send a sticky broadcast to check if it really works are not. 

To send a sticky broadcast message our application has to take permission "android.permission.BROADCAST_STICKY".

What is sticky broadcast?
The broadcast that will stick with android, and will be re-delivered or re-broadcasted to the future requests from any broadcast receivers.

To understand a sticky broadcast, consider below scenario.
We are writing a game application where if battery goes down, then we will save the user score and close the application.
In the above requirement, we will close our application and save the score only 
i. if user is currently playing the game.
ii. and batter went down.

So we have to write a broadcast receiver in our application which gets triggered for BATTERY_LOW broadcast.
In our broadcast receiver, we will save the current score of the user and display a popup saying we are closing the application as battery is going down.
But remember, if user is not playing the game, then there is no point of starting our receiver.
If we write our receiver in static way (in manifest file), then our receiver will be triggered irrespective of whether user is playing our game or not. But this not what we really want. We want our broadcast receiver has to be triggered only if user is playing our game currently and battery went down.

So, we have to use dynamic receivers in our application.

Now coming to the next scenario, assume that currently it is 10am and battery went down and system has send a broadcast to all applications saying BATTERY_LOW. But assume that at that point of time user is not playing our game, and hence our receiver will not be triggered as it is dynamic receiver.

Now what will happen if user starts our application at later point of time after 10am (let us say 10:05am). Should our dynamic receiver be triggered and show a popup to the user? 
Answer would be yes, because battery is going down since 10am. But the problem is system has already sent a broadcast at 10am, at which point of time our application was not running. So as far as our application is concerned that battery low event never happened. 

This is a kind of loop hole. To solve this problem, android introduced sticky boradcasts. On sending a sticky broadcast like BATTERY_LOW that intent will stick with android system and will be redelivered to later users(applications) who requests for similar kind of action.

In our case, at 10:05am once our application is started by user, we will request android if BATTERY_LOW happened by registering our dynamic receiver. If it has happened then android will trigger our receiver immediately.

Note: sticky broadcasts mechanism works only with dynamic receivers. For normal receivers it works just like a normal broadcast.

Note: Intent used with sticky broadcast is called as sticky intent. Because that intent will stick with android for future users


First Activity:

package com.techpalle.b15_sticky;

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 {
 Button b1, b2;
 private BroadcastReceiver br = new BroadcastReceiver() {
  
  @Override
  public void onReceive(Context context, Intent intent) {
   // TODO Auto-generated method stub
   Toast.makeText(context, "got it..", 0).show();
  }
 };
 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.STICK");
  
  b1.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent in = new Intent();
    in.setAction("com.techpalle.STICK");
    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;
 }

}

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_below="@+id/textView1"  
     android:layout_marginTop="16dp"  
     android:text="Send" />  
   <Button  
     android:id="@+id/button2"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignLeft="@+id/button1"  
     android:layout_below="@+id/button1"  
     android:layout_marginTop="68dp"  
     android:text="Register" />  
 </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_sticky"  
   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_sticky.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>  
 <uses-permission android:name="android.permission.BROADCAST_STICKY"/>  
 </manifest>  

Download complete code : Click to download

Android Interview questions related to Sticky broadcast receivers:
Difference between broadcast, sendorderedbroadcast, and sendstickybroadcast?
How to send battery low broadcast?
Difference between Intent, Sticky Intent, and Pending Intent?

Tags: android, sticky broadcast, receivers, sticky, dynamic receivers, sticky intent, permission, BROADCAST_STICKY.

Own a smart phone or laptop with best offers:

Ordered broadcast receivers:Android tutorial

Program description:

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

This program contains one activity, and 3 receivers.
Activity has a button, on clicking which we will send an ordered broadcast with implicit intent with action com.techpalle.RECEIVERS. All the 3 receiver will be having same intent filter with this matching action in them. But only difference is Receiver3 has priority-10, Receiver1 has priority-3, Receiver2 has priority-2. So the order of execution is with highest priority number to least priority number. 

So, Receiver3 executed first, then Receiver1 and then Receiver2. 

Note: If multiple receivers have same priority then android will choose to execute them in any random order.

Types of broadcasts: 3 types
1. Normal broadcasts - by using sendBroadcast()
2. Ordered broadcasts - by using sendOrderedBroadcast()
3. Sticky broadcasts - by using sendStickyBroadcast()

Normal broadcasts: by using sendBroadcast() method we can send normal broadcasts with an intent. If multiple components (receivers) are satisfying the intent given in the broadcast then android will start all the receivers in any order (randomly or simultaneously or one by one). 
Check this link for normal broadcasts

Ordered broadcasts: With ordered broadcasts programmer has the control over the order in which a receiver can be executed.
You can prioritize the order by giving priority attribute in the intent-filter tag of receiver tag in manifest file. More the priority number, higher the priority.
Along with prioritizing the order, we can also abort a broadcast in between and stop it going to the next receivers. With normal broadcasts we don't have this option.

Sticky broadcasts: Intent that is broadcasted with sendStickyBroadcast() will be stick with android for future users. (Future registerReceiver requests).

First Activity:

package com.techpalle.b15_rectypes;

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();
    in.setAction("com.techpalle.RECEIVERS");
    sendOrderedBroadcast(in, null);
   }
  });
 }

 @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:layout_marginTop="39dp"  
     android:text="Send broadcast.." />  
 </RelativeLayout>  

Broadcast Receiver
File name : Receiver1.java


package com.techpalle.b15_rectypes;

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

public class Receiver1 extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
     // TODO Auto-generated method stub
  String res = getResultData();
  Toast.makeText(context, "RCVR 1.."+res, 0).show();
 }
}

Broadcast Receiver
File name : Receiver2.java

package com.techpalle.b15_rectypes;

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

public class Receiver2 extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
     // TODO Auto-generated method stub
  String res = getResultData();
  Toast.makeText(context, "RCVR 2.."+res, 0).show();
 }
}

Broadcast Receiver
File name : Receiver3.java

package com.techpalle.b15_rectypes;

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

public class Receiver3 extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
     // TODO Auto-generated method stub
  Toast.makeText(context, "RCVR 3", 0).show();
  //abortBroadcast();
  setResultData("Hey..");
 }
}

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_rectypes"  
   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_rectypes.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="Receiver1">  
       <intent-filter android:priority="3">  
         <action android:name="com.techpalle.RECEIVERS"/>  
       </intent-filter>  
     </receiver>  
     <receiver android:name="Receiver2">  
       <intent-filter android:priority="2">  
         <action android:name="com.techpalle.RECEIVERS"/>  
       </intent-filter>  
     </receiver>  
     <receiver android:name="Receiver3">  
       <intent-filter android:priority="10">  
         <action android:name="com.techpalle.RECEIVERS"/>  
       </intent-filter>  
     </receiver>  
   </application>  
 </manifest>  

Download complete code : Click to download

Android interview questions on Ordered broadcast receivers:
Difference between Normal broadcast, ordered broadcast, and sticky broadcast?

Tags: android, ordered, broadcast receivers, priority

SD cards with best prices:

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


Broadcast receiver with implicit intent: Android tutorial

Program description:

This is one more program on how to create a broadcast receiver and how to send a broadcast message by using implicit intent.


This program has an activity, and 2 receivers. Activity has one button. On clicking the button an implicit intent will be used to send a broadcast with action com.techpalle.action.RECEIVER1.
This will trigger Receiver1. In Reciever1 we will send one more broadcast with an implicit intent with action com.techpalle.action.RECEIVER2. While sending this broadcast we will generate a random number between 0 to 100, and send that number as extra information in the intent.
This will trigger Receiver2, which displays random number passed from first broadcast receiver.

This program also has a demo of how to send a broadcast from one broadcast receiver to other broadcast receiver, by using implicit intent.

First Activity:

package com.techpalle.b15_asg_receivers;

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) {
    // TODO Auto-generated method stub
    Intent in = new Intent();
    in.setAction("com.techpalle.action.RECEIVER1");
    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 : Receiver1.java

package com.techpalle.b15_asg_receivers;

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

public class Receiver1 extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
     // TODO Auto-generated method stub
  Toast.makeText(context, "first app..receiver1", 0).show();
  Intent in = new Intent();
  in.setAction("com.techpalle.action.RECEIVER2");
  int ran = (int) (Math.random()*100);
  in.putExtra("ran", ran);
  context.sendBroadcast(in);
 }
}

Broadcast receiver
File name : Receiver2.java

package com.techpalle.b15_asg_receivers;

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

public class Receiver2 extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
 int ran = intent.getExtras().getInt("ran");
 Toast.makeText(context, "First app..recvr2..ran.."+ran, 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_asg_receivers"  
   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_asg_receivers.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="Receiver1">  
       <intent-filter >  
         <action android:name="com.techpalle.action.RECEIVER1"/>  
       </intent-filter>  
     </receiver>  
     <receiver android:name="Receiver2">  
       <intent-filter >  
         <action android:name="com.techpalle.action.RECEIVER2"/>  
       </intent-filter>  
     </receiver>  
   </application>  
 </manifest>  

Download complete code : Click to download

Interview questions on broadcast receivers:
Broadcast receiver runs in which thread?
Is it possible to bind a service from receiver?

Tags: android, broadcast receiver, sendbroadcast, implicit intent

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

Wednesday, December 18, 2013

Using implicit intent: Android tutorial

Program description:

This is a demo program on how to start an activity by using implicit intent.

This program has 2 activities, first activity will start second activity by using implicit intent.
First activity has 2 buttons, on clicking first button we use implicit intent to trigger second activity. This implicit intent uses 1 action and 2 categories.
On clicking second button, it will start same second activity by using explicit intent.

Once second activity is triggered, it will display the action, and categories which has triggered that activity by using getIntent() method.

Intents are 2 types: Explicit intent, and implicit intent.

1.Explicit intent : An intent which contains target component name in it. We generally use explicit intent to communicate between components of same application.
2.Implicit intent : An intent which doesn't contain target component name. Since there is no target component name, we have to provide some clues to android to trigger a component. Those clues will be in the form of action, categories, and data. We generally use implicit intent to communicate with other application components, as we don't know their component names. 

This example will demonstrate both implicit and explicit intent.

difference between explicit and implicit intent


First activity

package com.techpalle.b15_test3;

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 b1, b2;
 @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);
  b1.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent in = new Intent();
    in.setAction("com.techpalle.action.MYACTION");
    in.addCategory("com.techpalle.category.MYCATEGORY");
    in.addCategory("com.techpalle.category.MYCATEGORY2");
    startActivity(in);
   }
  });
  b2.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent in = new Intent(getApplicationContext(),
      SecondScreen.class);
    startActivity(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:layout_marginLeft="52dp"  
     android:layout_marginTop="36dp"  
     android:text="Start second implicit" />  
   <Button  
     android:id="@+id/button2"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignLeft="@+id/button1"  
     android:layout_below="@+id/button1"  
     android:layout_marginTop="30dp"  
     android:text="Start second explicit" />  
 </RelativeLayout>  

Second activity

package com.techpalle.b15_test3;

import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class SecondScreen extends Activity {

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     TextView tv = new TextView(this);
     tv.setText("hey..");
     setContentView(tv);
     Intent in = getIntent();
     if(in != null){
      String action = in.getAction();
      Set cat = in.getCategories();
      Toast.makeText(getApplicationContext(), "action.."+action, 
        0).show();
      Toast.makeText(getApplicationContext(), "cat.."+cat, 
        0).show();
     }
     // TODO Auto-generated method stub
 }

}

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_test3"  
   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_test3.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>  
     <activity android:name="SecondScreen">  
       <intent-filter >  
         <action android:name="com.techpalle.action.MYACTION"/>  
         <category android:name="com.techpalle.category.MYCATEGORY"/>  
         <category android:name="com.techpalle.category.MYCATEGORY2"/>  
         <category android:name="android.intent.category.DEFAULT"/>  
       </intent-filter>  
     </activity>  
   </application>  
 </manifest>  

Download complete code : Click to download

Android interview questions on Intents:
What is the difference between implicit intent and explicit intent?
What are the components of an intent?
What is putExtra in intent?
What is the difference between intent, pending intent, and sticky intent?
Is it possible to have extras in intent-filter?
What is the difference between intent and intent-filter?
How intent and intent-filter works in android? What is intent test?



Tags: android, implicit, intent, explicit, getIntent

How to make phone call from android program: Android tutorial

Program description:

This is a demo program on how to make a phone call from an android application on button click.

For this we will use ACTION_CALL in the intent, and pass the the Uri which contains phone number to make the call. On clicking the button it will launch the call application.

Note : It requires android permission "android.permission.CALL_PHONE".

First activity


package com.techpalle.b15_call;

import android.net.Uri;
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();
    in.setAction(Intent.ACTION_CALL);
    Uri myUri = Uri.parse("tel:12345");
    in.setData(myUri);
    startActivity(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" >  
   <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentLeft="true"  
     android:layout_alignParentTop="true"  
     android:layout_marginLeft="60dp"  
     android:text="Call" />  
 </RelativeLayout>  

Download complete code : Click to download

Tags: android, make phone call