Technical Knowledge

technical knowledge is that type of blogger in which you can find all the soluctions of your problems which you cannot solve you can see the video given on this blog and solve your problem by yourself.

Like us on Facebook

Technical Knowledge
Showing posts with label Broadcast. Show all posts
Showing posts with label Broadcast. Show all posts

Sunday, March 29, 2015

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

  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" >

Manifest file
File name : AndroidManifest.xml

  
package="com.techpalle.b15_rcvr_asg1"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_rcvr_asg1.MainActivity"
android:label="@string/app_name" >








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

  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" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

Manifest file (for second application)
File name : AndroidManifest.xml

  
package="com.techpalle.b15_rcvr_asg1_app2"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_rcvr_asg1_app2.MainActivity"
android:label="@string/app_name" >









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.

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

  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" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

Manifest file
File name : AndroidManifest.xml

  
package="com.techpalle.b15_dynrec"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_dynrec.MainActivity"
android:label="@string/app_name" >








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

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


  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" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

Manifest file
File name : AndroidManifest.xml


  
package="com.techpalle.b15_sticky"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_sticky.MainActivity"
android:label="@string/app_name" >









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.

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

  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" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />


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


  
package="com.techpalle.b15_asg_receivers"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_asg_receivers.MainActivity"
android:label="@string/app_name" >


















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

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

  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" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

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


  
package="com.techpalle.b15_broadcastreceivers"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_broadcastreceivers.MainActivity"
android:label="@string/app_name" >









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

Older Posts Home