Thursday, January 30, 2014

Repeating alarms with irregular intervals : Android tutorial

Program description:

This program will demo how to create alarms which will repeat at irregular intervals.

This program has one activity with one button, and a broadcast receiver.
On clicking the button, we will set an alarm for next 1 second, which triggers broadcast receiver.
Our program aim is to repeat next alarm at 2 seconds, next at 4 seconds, next at 8 seconds and so on.. For this requirement we can't use setRepeating() function of alarm manager.
We have to set the alarm manually in the receiver.

Once the first alarm (which was set for 1 second) is triggered, it will call broadcast receiver. In the receiver set alarm for next 2 seconds from that time. Which will again call same broadcast receiver after 2 seconds. Again set one more alarm for next 4 seconds in that receiver. For this we have to write a generic logic, because alarm has to repeat for n number of times.

First Activity:


package com.techpalle.b15_alarm_asg2;

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

public class MainActivity extends Activity {
 AlarmManager am;
 Button b;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
  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.ALARM_INDEF");
    int i=1;
    in.putExtra("val", i);
    PendingIntent pi = PendingIntent.getBroadcast(
      getApplicationContext(), 
      0, 
      in, 
      0);
    am.set(AlarmManager.RTC_WAKEUP, 
      System.currentTimeMillis()+1000, 
      pi);
    
   }
  });
 }

 @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
 public boolean onOptionsItemSelected(MenuItem item) {
  // TODO Auto-generated method stub
  return super.onOptionsItemSelected(item);
 }

}

Broadcast receiver 
File name : AlarmRecvr.java


package com.techpalle.b15_alarm_asg2;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.ViewDebug.FlagToString;
import android.widget.Toast;

public class AlarmRecvr extends BroadcastReceiver {
 //public static int i = 1;
 @Override
 public void onReceive(Context context, Intent intent) {
     int i = intent.getExtras().getInt("val");
     i = i*2;
     Toast.makeText(context, "Got", 0).show();
     Intent in = new Intent();
     in.setAction("com.techpalle.action.ALARM_INDEF");
     in.putExtra("val", i);
     PendingIntent pi = PendingIntent.getBroadcast(
       context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
     AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
     am.set(AlarmManager.RTC_WAKEUP, 
       System.currentTimeMillis()+(i*1000),
       pi);     
 }
}

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="41dp"  
     android:layout_marginTop="70dp"  
     android:text="Start alarms.." />  
 </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_alarm_asg2"  
   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_alarm_asg2.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="AlarmRecvr">  
       <intent-filter >  
         <action android:name="com.techpalle.action.ALARM_INDEF"/>  
       </intent-filter>  
     </receiver>  
   </application>  
 </manifest>  

Download complete code : Click to download

Android interview questions on Power manager and wake locks:
What is sleep mode? What will happen to CPU when LCD is turned off?
What are the two components that runs in Sleep mode also?
Every day night at 12 o clock I need to post some images to Facebook, in that case I will set repeating alarm for every day night 12 am. But to upload images I want to start service, how should I do this ?
What is the difference between Intent, Sticky Intent, and Pending Intent?


Wednesday, January 29, 2014

Repeating alarms : Android tutorial

Program description:

This program will demo how to create repeating alarms, which will trigger broadcast receivers.


This program has one activity with one button, and a broadcast receiver.
On clicking the button we will set an alarm which will trigger after 5 seconds from now.
That alarm will keep repeating for every next 5 seconds. Every time it triggers it will send a broadcast receiver. Broadcast receiver will print "got" message for every 5 seconds.

Before using this program, you should know  how to create alarms with broadcast receiver.

First Activity


package com.techpalle.b15_alarm_asg1;

import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
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 {
 AlarmManager am;
 Button b;
 ActivityManager acm;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  acm = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
  List l = acm.getRunningTasks(10);

  b = (Button) findViewById(R.id.button1);
  am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
  b.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent in = new Intent();
    in.setAction("com.techpalle.action.ALARM_REPEAT");
    PendingIntent pi = PendingIntent.getBroadcast(
      getApplicationContext(),
      0, in, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, 
      System.currentTimeMillis()+5000,
      5000, 
      pi);
   }
  });
 }

 @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;
 }

}

Broadcast receiver 
File name : AlarmRecvr.java
package com.techpalle.b15_alarm_asg1;

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

public class AlarmRecvr extends BroadcastReceiver {

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

}

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_toRightOf="@+id/textView1"  
     android:text="Start repeating.." />  
 </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_alarm_asg1"  
   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_alarm_asg1.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="AlarmRecvr">  
       <intent-filter >  
         <action android:name="com.techpalle.action.ALARM_REPEAT"/>  
       </intent-filter>  
     </receiver>  
   </application>  
 </manifest>  
hi

Download complete code : Click to download

Android interview questions on Power manager and wake locks:
What is sleep mode? What will happen to CPU when LCD is turned off?
What are the two components that runs in Sleep mode also?
Every day night at 12 o clock I need to post some images to Facebook, in that case I will set repeating alarm for every day night 12 am. But to upload images I want to start service, how should I do this ?
What is the difference between Intent, Sticky Intent, and Pending Intent?

Using alarms : Android tutorial

Program description:

This program will demo how to create alarms with broadcast receiver.

This program has one activity and one static broadcast receiver. Activity has a button, on clicking that we will set an alarm which will expire after 5 seconds from now. Once alarm is triggered it will send a broadcast with action "com.techpalle.action.ALARM_RECEIVER".
Once broadcast receiver is triggered, it will show a toast message "alarm tirggered".

In order to send a broadcast by using alarms, here we will use pending intents.

Pending intent: It is used to perform intent operations at future point of time on our behalf by some one else (mostly by alarm manager or notification manager).

Broadcast will be send after 5 seconds from the time of button click. It will be send by alarm manager. Since we are not sending broadcast immediately, and it is sent after 5 seconds. So our intent to send broadcast will be pending till then. That's why it is called as pending intent.

Steps to do this alarm program with broadcast receiver in android:
1. Create a broadcast receiver that will be triggered/ called after 5 seconds.
2. Come to activity java file, Create alarm manager object by using getSystemService() method.
3. Create intent to send a broadcast.
4. Create pending intent to shoot a broadcast from above created intent.
5. set the alarm for next 5 seconds by using alarm manager and pass pending intent.

First Activity:

package com.techpalle.b15_alarms;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
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;
 AlarmManager am;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  b = (Button) findViewById(R.id.button1);
  //step1 : create alarm manager
  am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
  b.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    //a. create intent
    Intent in = new Intent();
    in.setAction("com.techpalle.action.ALARM_RECEIVER");
    //b. create pending intent
    PendingIntent pi = PendingIntent.getBroadcast(
      getApplicationContext(), 
      0, 
      in, 
      0);
    //c. set alarm for 5 seconds.
    am.set(AlarmManager.RTC_WAKEUP, 
      System.currentTimeMillis()+5000, 
      pi);
    
    
   }
  });
 }
}

Broadcast receiver 
File name : AlarmRecvr.java

package com.techpalle.b15_alarms;

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

public class AlarmRecvr extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
     Toast.makeText(context, "Got the alarm..", 0).show();
 }
}

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="24dp"  
     android:layout_marginTop="17dp"  
     android:text="Send broadcast after 5 seconds" />  
 </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_alarms"  
   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_alarms.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="AlarmRecvr">  
       <intent-filter >  
         <action android:name="com.techpalle.action.ALARM_RECEIVER"/>  
       </intent-filter>  
     </receiver>  
   </application>  
 </manifest>  

Download complete code : Click to download

Android interview questions on Power manager and wake locks:
What is sleep mode? What will happen to CPU when LCD is turned off?
What are the two components that runs in Sleep mode also?
Every day night at 12 o clock I need to post some images to Facebook, in that case I will set repeating alarm for every day night 12 am. But to upload images I want to start service, how should I do this ?
What is the difference between Intent, Sticky Intent, and Pending Intent?

How to use Wake locks: android tutorial

Program description:

This program will demo how to use wake locks in android.

Before seeing the demo program lets understand what is wake lock and sleep mode.

Major difference between phones and laptops (In terms of power):
Laptops mostly work on direct power through charger. Most of the times we carry power cables while using laptops.
Phones mostly work on battery power. Very rarely we carry phone chargers along with us while going out. 
That means phones rely heavily on battery power, where as for laptops there is no such constraint.
Based on this assumption, we can come to a conclusion that phones should use battery very efficiently in order to increase battery back up time.
Meaning, programmers should write code to consume less battery power.

Sleep mode:
Based on above theory, android has done some major changes in the power manager driver of O.S layer. If user is not using the phone, then automatically LCD or screen of the phone will be turned off. With in fraction of seconds CPU will go to sleep mode. This is done in order to increase battery life in phones. 
Note: If LCD of phone is turned off means, user is not using or not viewing at the phone. So when user is not using the phone, there is no point in keeping CPU running. That's why with in fraction of seconds CPU will be moved to sleep mode, and stops consuming battery power.

What components works when CPU is in sleep mode?
When CPU is in sleep mode, only Alarms & RIL (Radio interface layer) components works.
RIL : includes Calls, sms, mms, internet connection.
Apart from these components, nothing else will work.
Note: In android if we switch off the phone, all the alarms will be destroyed.

If CPU is in sleep mode, does my application stops working?
When CPU is in sleep mode, all the applications will be moved to suspended state. They will be resumed once LCD is turned on (which makes CPU to turn on).

So I can't run my application when CPU is in sleep mode?
You can request CPU to wake up by using wake locks, to run your application components.

Wake locks:
Wake locks are used to wake up the CPU from sleep mode, and perform some important tasks which are useful to user.
eg: I want to book tickets in IRCTC at late night 11pm. Mostly at 11pm user will be sleeping, so LCD will be turned off, which makes CPU to sleep mode. But still you can wake up CPU by using wake locks and book tickets in the back ground and then release the wake locks.

Types of wake locks:
There are 4 types of wake locks available in android.
1. PARTIAL_WAKE_LOCK : by using this only CPU will be turned on. eg: use partial wake lock, to play songs while in the journey.
2. SCREEN_DIM_WAKE_LOCK : by using this CPU, and LCD will turned on. But LCD will be in dim mode. eg: use this wake lock to see the time.
3. SCREEN_BRIGHT_WAKE_LOCK : by using this CPU, and LCD will be turned on. LCD will be in full bright mode. eg: use this wake lock to watch a movie.
4. FULL_WAKE_LOCK : by using this CPU, LCD, and Keypad will be on. eg: use this wake lock to play a game.

Below is a sample demo program on how to use PARTIAL_WAKE_LOCK.

Note: to use wake locks, programmer has to take android.permission.WAKE_LOCK.
else program will crash with security exception.

First Activity:

package com.techpalle.b15_testpower;

import android.os.Bundle;
import android.os.PowerManager;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;

public class MainActivity extends Activity {
 PowerManager pm;
 PowerManager.WakeLock wl;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
  wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "satish");
  
  wl.acquire();
  //...
  wl.release();
 }
}

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" >  
 </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_testpower"  
   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_testpower.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.WAKE_LOCK"/>  
 </manifest>  

Download complete code : Click to download

Android interview questions on Power manager and wake locks:
What is sleep mode? What will happen to CPU when LCD is turned off?
What are the two components that runs in Sleep mode also?

Wednesday, January 15, 2014

Ordered broadcast receiver assignment: android tutorial

Program description:

This is an assignment program on using ordered broadcast receiver. This assignment has 2 applications. 


Assignment description: 
First application is having one activity, and 2 broadcast receivers (static).
Both the receivers have an intent filter with action "com.techpalle.action.ORDERED".
But Receiver1 has android:priority="1", and Receiver2 has android:priority="3".
In this first application first activity has a button to send ordered broadcast with action "com.techpalle.action.ORDERED". 

As you already know there are 3 types of broadcast receivers are there in android.

Note: More the priority number, higher the priority. Higher priority receivers will be executed first.

Second application has one activity, and 1 broadcast receiver (static).
This receiver has intent filter with same action "com.techpalle.action.ORDERED".
This Receiver3 has android:priority="2".

Assumption: It is assumed that the second application should be already in the phone or emulator. So make sure that you first run the second application and then first application.

Now once user runs the first application, and clicks the button on the first activity it will send an ordered broadcast. Now there are 3 receivers are matching with the intent action in their intent-filter. So all the 3 broadcast receiver's onReceive()  method will be executed.

But since we are using ordered broadcast, first highest priority receiver will be executed. 

So Receiver2 of application1 will get executed first. (priority 3)
In the Receiver2, we are generating a random number between 0 to 100, and passing this as data to next receiver. (by using setResultCode() method).

Receiver3 of second application has next priority (priority 2), so that receiver will be called.
In the Receiver3 we will receive the data send by Receiver2 of first application. (by using getResultCode() method).

In the Receiver3 we will check if the data is even or odd. If it is even then we are stopping that broadcast in Receiver3 itself by using abortBroadCast() method. If not Receiver1 of first application will continue.

First Application's First Activity:

package com.techpalle.b15_rcvr_asg2;

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.action.ORDERED");
    sendOrderedBroadcast(in, null);    
   }
  });
 }

}

First Application's Broadcast Receiver 1:

package com.techpalle.b15_rcvr_asg2;

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

public class Recvr1 extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
     int data = getResultCode();
     Toast.makeText(context, "receiver 1..data.."+data, 0).show();
 }
}

First Application's Broadcast Receiver 2:
package com.techpalle.b15_rcvr_asg2;

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

public class Recvr2 extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  Toast.makeText(context, "receiver 2..", 0).show();
     int ran = (int) (Math.random()*100);
     setResultCode(ran);
 }
}

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>  

First application's Manifest file (to check the priorities of the receivers)
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_rcvr_asg2"  
   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_rcvr_asg2.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="Recvr1">  
       <intent-filter android:priority="1">  
         <action android:name="com.techpalle.action.ORDERED"/>  
       </intent-filter>  
     </receiver>  
     <receiver android:name="Recvr2">  
       <intent-filter android:priority="3">  
          <action android:name="com.techpalle.action.ORDERED"/>  
       </intent-filter>  
     </receiver>  
   </application>  
 </manifest>  

Second Application's First Activity:

package com.techpalle.b15_rcvr_asg2_app2;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 }
}

Second Application's Broadcast Receiver 3:

package com.techpalle.b15_rcvr_asg2_app2;

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

public class Recvr3 extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
     int data = getResultCode();
     if(data % 2 != 0){
      abortBroadcast();
     }
     Toast.makeText(context, "receiver 3..data.."+data, 0).show();
 }

}

Second application's Manifest file (to see the priority)
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_rcvr_asg2_app2"  
   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_rcvr_asg2_app2.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="Recvr3">  
       <intent-filter android:priority="2">  
         <action android:name="com.techpalle.action.ORDERED"/>  
       </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

Sticky broadcast receiver assignment: android tutorial

Program description:

This is an assignment program on using sticky broadcast receiver. This assignment has 2 applications. 

First application will be having one activity with one button. This activity also has a dynamic receiver which will be registered on clicking that button. 
Second application is also having one activity with one button. A sticky broadcast will be fired on clicking that button.

First user will open second application and clicks on the button to send a sticky broadcast to send a broadcast with action "com.techpalle.action.STICKY".

Then user will open first application's activity and click the button to register for receiver for an action "com.techpalle.action.STICKY". Once user clicks on the button to register dynamic receiver with an action which was previously broadcasted by second application, android will immediately call the onReceive() method of the current application's dynamic receiver. Reason for this is, sticky broadcasts will stick with android for future users.

Wanted to know more about what exactly is a sticky broadcast?

First Application's First activity:

package com.techpalle.b15_rcvr_asg1;

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) {
   Toast.makeText(context, "Triggered..", 0).show();   
  }
 };
 private IntentFilter inf;
 Button b;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  inf = new IntentFilter();
  inf.addAction("com.techpalle.action.STICKY");
  
  b = (Button) findViewById(R.id.button1);
  b.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    registerReceiver(br, inf);
   }
  });
 }
 
 @Override
 protected void onDestroy() {
  unregisterReceiver(br);
  super.onDestroy();
 }

}

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="33dp"  
     android:layout_marginTop="28dp"  
     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_rcvr_asg1"  
   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_rcvr_asg1.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>  

Second Application's First activity:

package com.techpalle.b15_rcvr_asg1_app2;

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.action.STICKY");
    sendStickyBroadcast(in);
   }
  });
 }

}

xml file for first activity (second application)
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="53dp"  
     android:layout_marginTop="21dp"  
     android:text="Send Sticky Broadcast" />  
 </RelativeLayout>  

Manifest file (for second application)
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_rcvr_asg1_app2"  
   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_rcvr_asg1_app2.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.

Saturday, January 11, 2014

Dynamic receivers: android tutorial

Program description:

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

This program has an activity with 2 buttons. This activity has a dynamic broadcast receiver created in it.
On clicking first button we will send a broadcast with action "DYNAMIC_RECEIVER".
On clicking second button we will register dynamic receiver with an intent filter that has action "DYNAMIC_RECEIVER".

First Activity:

package com.techpalle.b15_dyn_receivers;

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;
 
 //step1 : create a dynamic b.c.receiver in java code
 private BroadcastReceiver br = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
   Toast.makeText(context, "Dyn receiver triggered", 0).show();
  }
 };
 //step2 : create intent filter
 private IntentFilter inf;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  b1 = (Button) findViewById(R.id.button1); //sending b.c
  b2 = (Button) findViewById(R.id.button2); //register receiver
  
  //prepare intent filter by adding the action.
  inf = new IntentFilter();
  inf.addAction("DYNAMIC_RECEIVER");
  
  b1.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent in = new Intent();
    in.setAction("DYNAMIC_RECEIVER");
    sendBroadcast(in);    
   }
  });
 
  //step3 : register brodacast receiver with intent filter
  b2.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    registerReceiver(br, inf);
   }
  });  
 }
}

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="20dp"  
     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: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_dyn_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_dyn_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>  
   </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

Smartphones