How to use a broadcast receiver
satya - Tuesday, May 11, 2010 9:47:45 AM
How to use android broardcast receiver
How to use android broardcast receiver
satya - Tuesday, May 11, 2010 9:50:34 AM
Class documentation for BroadcastReceiver
satya - Wednesday, May 12, 2010 10:29:24 PM
NotificationManager
NotificationManager
satya - Wednesday, May 12, 2010 10:33:17 PM
See if there are any examples in samples
See if there are any examples in samples
satya - Wednesday, May 12, 2010 10:37:38 PM
Some introductory notes on broadcast receiver usage
satya - Wednesday, May 12, 2010 10:40:22 PM
useful android broadcast intents
useful android broadcast intents
satya - Wednesday, May 12, 2010 10:46:58 PM
You can find standard broadcast intent actions here at this link for Intent class
You can find standard broadcast intent actions here at this link for Intent class
satya - Wednesday, May 12, 2010 10:47:45 PM
Some examples
ACTION_TIME_TICK
ACTION_TIME_CHANGED
ACTION_TIMEZONE_CHANGED
ACTION_BOOT_COMPLETED
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION_PACKAGE_REMOVED
ACTION_PACKAGE_RESTARTED
ACTION_PACKAGE_DATA_CLEARED
ACTION_UID_REMOVED
ACTION_BATTERY_CHANGED
ACTION_POWER_CONNECTED
ACTION_POWER_DISCONNECTED
ACTION_SHUTDOWN
satya - Wednesday, May 12, 2010 10:52:28 PM
A good one to test:ACTION_WALLPAPER_CHANGED
satya - Wednesday, May 12, 2010 11:00:01 PM
WallPaperManager
WallPaperManager
satya - Saturday, May 15, 2010 1:28:37 PM
API samples has an example: AlarmController.java
API samples has an example: AlarmController.java
satya - Saturday, May 15, 2010 1:34:18 PM
You may want to understand how pending intents works: look here
You may want to understand how pending intents works: look here
satya - Saturday, May 15, 2010 1:48:29 PM
How is a broadcast receiver configured in the manifest file?
How is a broadcast receiver configured in the manifest file?
Search for: How is a broadcast receiver configured in the manifest file?
satya - Saturday, May 15, 2010 1:56:48 PM
The tag for a receiver in the manifest file is here
The tag for a receiver in the manifest file is here
Caution: Note that this is a large document at that link. it may take sometime to get loaded if you are on a slow connection
satya - Saturday, May 15, 2010 1:59:26 PM
order of tags
<application>
<receiver name="classname" ...>
<intent-filter>
satya - Saturday, May 15, 2010 2:03:45 PM
Couple of samples
<receiver android:name=".app.OneShotAlarm" android:process=":remote" />
<receiver android:name=".app.RepeatingAlarm" android:process=":remote" />
<receiver android:name=".appwidget.ExampleBroadcastReceiver" android:enabled="false">
<intent-filter>
<action android:name="android.intent.ACTION_TIMEZONE_CHANGED" />
<action android:name="android.intent.ACTION_TIME" />
</intent-filter>
</receiver>
<receiver android:name=".appwidget.ExampleAppWidgetProvider">
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/appwidget_provider" />
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
</receiver>
satya - Saturday, May 15, 2010 2:06:17 PM
A sample receiver class
public class ExampleBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("ExmampleBroadcastReceiver", "intent=" + intent);
// For our example, we'll also update all of the widgets when the timezone
// changes, or the user or network sets the time.
String action = intent.getAction();
if (action.equals(Intent.ACTION_TIMEZONE_CHANGED)
|| action.equals(Intent.ACTION_TIME_CHANGED)) {
AppWidgetManager gm = AppWidgetManager.getInstance(context);
ArrayList<Integer> appWidgetIds = new ArrayList<Integer>();
ArrayList<String> texts = new ArrayList<String>();
ExampleAppWidgetConfigure.loadAllTitlePrefs(context, appWidgetIds, texts);
final int N = appWidgetIds.size();
for (int i=0; i<N; i++) {
ExampleAppWidgetProvider.updateAppWidget(context,
gm, appWidgetIds.get(i), texts.get(i));
}
}
}
}
satya - Sunday, May 16, 2010 10:14:34 PM
what does broadcastreceiver process attribute stand for?
what does broadcastreceiver process attribute stand for?
Search for: what does broadcastreceiver process attribute stand for?
satya - Sunday, May 16, 2010 10:15:13 PM
Perhaps we can look at AndroidManifestReceiver
Perhaps we can look at AndroidManifestReceiver
satya - Sunday, May 16, 2010 10:15:28 PM
AndroidManifestReceiver
AndroidManifestReceiver
satya - Sunday, May 16, 2010 10:18:42 PM
The docs for the receiver element
satya - Sunday, May 16, 2010 10:26:33 PM
Various attributes: exported
exported: is it accessible just inside the application or across applications. If there are not intent filters, then the sender must explicitly invoke the receiver by its classname.
If there are intent filters the default is true to allow actions from other apps to be received. If there are no intent filters then the default is false, and to disallow the receiver outside.
satya - Sunday, May 16, 2010 10:27:16 PM
Why use a broadcastreceiver with explicit classname at all?
Why use a broadcastreceiver with explicit classname at all?
Search for: Why use a broadcastreceiver with explicit classname at all?
satya - Sunday, May 16, 2010 10:28:53 PM
attribute enabled
default is true, and if false this receiver will not be instantiated.
satya - Sunday, May 16, 2010 10:29:28 PM
why allow broadcastreceiver without intent filters?
why allow broadcastreceiver without intent filters?
Search for: why allow broadcastreceiver without intent filters?
satya - Sunday, May 16, 2010 10:32:16 PM
why is there label and icon for a broadcastreceiver
why is there label and icon for a broadcastreceiver
Search Google for: why is there label and icon for a broadcastreceiver
Search Android Developers Group for: why is there label and icon for a broadcastreceiver
Search Android Beginers Group for: why is there label and icon for a broadcastreceiver
Search Google Code for: why is there label and icon for a broadcastreceiver
Search Android Issues Database for: why is there label and icon for a broadcastreceiver
satya - Sunday, May 16, 2010 10:36:53 PM
permission
the sender must have this permissions to send to this receiver. If not specified open to all
satya - Sunday, May 16, 2010 10:40:21 PM
android:process the curious animal
The name of the process in which the broadcast receiver should run. Normally, all components of an application run in the default process created for the application. It has the same name as the application package. The If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the broadcast receiver runs in that process. If the process name begins with a lowercase character, the receiver will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.
satya - Sunday, May 16, 2010 10:41:37 PM
what process in android is :remote
what process in android is :remote
Search Google for: what process in android is :remote
Search Android Developers Group for: what process in android is :remote
Search Android Beginers Group for: what process in android is :remote
Search Google Code for: what process in android is :remote
Search Android Issues Database for: what process in android is :remote
satya - Wednesday, May 19, 2010 11:21:34 PM
Does a broadcast receiver execute in the main thread
Does a broadcast receiver execute in the main thread
Search for: Does a broadcast receiver execute in the main thread
satya - Wednesday, May 19, 2010 11:21:55 PM
broadcastreceiver mainthread
broadcastreceiver mainthread
Search Google for: broadcastreceiver mainthread
Search Android Developers Group for: broadcastreceiver mainthread
Search Android Beginers Group for: broadcastreceiver mainthread
Search Google Code for: broadcastreceiver mainthread
Search Android Issues Database for: broadcastreceiver mainthread
satya - Thursday, May 20, 2010 10:18:35 AM
The following is a meaty thread to read on this subject
The following is a meaty thread to read on this subject
I will report the findings in a lil while
satya - Thursday, May 20, 2010 10:21:53 AM
Read this note on responsiveness and what happens to threads
Read this note on responsiveness and what happens to threads
satya - Thursday, May 20, 2010 10:29:23 AM
Here is a suggested pattern for a broadcast receiver
I don't think it's valid to start a Thread in a BroadcastReceiver. The system doesn't know anything about that thread, so it wouldn't know that it's supposed to keep the process hosting it around. My app nanoTweeter does similar background polling and I acquire the WakeLock in the BroadcastReceiver and then start a Service. That service releases the lock when it's done.
satya - Thursday, May 20, 2010 10:30:54 AM
Here is more on it
The alarm BroadcastReceiver's onReceive() acquires a WakeLock and stores it in a static field so that the Service can access it later. It then starts a Service using Context.startService().
The Service's onStart() creates a Handler for the main thread and then creates and runs a new Thread. That Thread does the important work then releases the WakeLock and calls Service.stopSelf() on the main thread via the Handler that was set up earlier.
satya - Thursday, May 20, 2010 10:32:33 AM
See if this source code link works: alarm clock example
satya - Thursday, May 20, 2010 11:01:03 AM
common tasks note on broadcast receivers
satya - Thursday, May 20, 2010 11:05:39 AM
an example
// We are sending this to a specific recipient, so we will
// only specify the recipient class name.
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("message","Wake up.");
sendBroadcast(intent);
satya - Thursday, May 20, 2010 11:06:44 AM
definition
<receiver class=".AlarmReceiver" />
satya - Thursday, May 20, 2010 11:09:30 AM
The class itself
public class AlarmReceiver extends BroadcastReceiver
{
// Display an alert that we've received a message.
@Override public void onReceive(Context context, Intent intent)
{
// Send a text notification to the screen.
NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notifyWithText(R.id.alarm,
"Alarm!!!",
NotificationManager.LENGTH_SHORT,
null);
}
}
satya - Thursday, May 20, 2010 11:10:45 AM
Use this link to discover telephony events
satya - Thursday, May 20, 2010 12:44:51 PM
broadcastreceiver UI thread
broadcastreceiver UI thread
Search Google for: broadcastreceiver UI thread
Search Android Developers Group for: broadcastreceiver UI thread
Search Android Beginers Group for: broadcastreceiver UI thread
Search Google Code for: broadcastreceiver UI thread
Search Android Issues Database for: broadcastreceiver UI thread
satya - Thursday, May 20, 2010 12:45:24 PM
This link below seem to suggest that broadcast receivers do run in the main ui thread
This link below seem to suggest that broadcast receivers do run in the main ui thread
satya - Thursday, May 20, 2010 12:47:11 PM
registerReceiver() differences
registerReceiver() differences
Search Google for: registerReceiver() differences
Search Android Developers Group for: registerReceiver() differences
Search Android Beginers Group for: registerReceiver() differences
Search Google Code for: registerReceiver() differences
Search Android Issues Database for: registerReceiver() differences
satya - Thursday, May 20, 2010 2:31:31 PM
Aha! it looks like it is a design choice that broadcast receivers must respond
A BroadcastReceiver hasn't finished executing within 10 seconds
satya - Thursday, May 20, 2010 2:32:29 PM
who controls ANR (App Not responding)
Activity Manager
Window Manager
satya - Thursday, May 20, 2010 2:33:34 PM
Criteria for ANR
1. No response to an input event (e.g. key press, screen touch) within 5 seconds
2. A BroadcastReceiver hasn't finished executing within 10 seconds
satya - Thursday, May 20, 2010 2:35:39 PM
Let's read this
Android applications normally run entirely on a single (i.e. main) thread.
This means that anything your application is doing in the main thread that takes a long time to complete can trigger the ANR dialog because:
1. your application is not giving itself a chance to handle the input event
2. or an Intent broadcast.
satya - Thursday, May 20, 2010 2:37:35 PM
Role of a handler
your main thread should provide a Handler for child threads to post back to upon completion.
satya - Thursday, May 20, 2010 2:38:26 PM
key event time out: 5 seconds
5 second input event timeout
satya - Thursday, May 20, 2010 2:40:59 PM
Again seems a design choice
The specific constraint on IntentReceiver execution time emphasizes what they were meant to do: small, discrete amounts of work in the background such as saving a setting or registering a Notification. So as with other methods called in the main thread, applications should avoid potentially long-running operations or calculations in BroadcastReceivers.
satya - Thursday, May 20, 2010 2:53:53 PM
Here is another indication that broadcast receivers are handled by main thread
When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create.
From the handler class documentation
satya - Thursday, May 20, 2010 10:49:51 PM
why would I use sendBroadcast with explicit classname?
why would I use sendBroadcast with explicit classname?
Search for: why would I use sendBroadcast with explicit classname?
satya - Monday, May 24, 2010 1:16:56 PM
Here is a simple broadcaset sender
You can invoke this code from a simple menu item.
private void testSendBroadcast()
{
//Print out what your running thread id is
Utils.logThreadSignature();
//Create an intent with an action
Intent i = new Intent("com.ai.android.intents.testbc");
//load up the intent with a message
//you want to broadcast
i.putExtra("message", "Hello world");
//send out the broadcast
//there may be multiple receivers receiving it
this.sendBroadcast(i);
//Log a message after sending the broadcast
//This message should appear first in the log file
//before the log messages from the broadcast
//because they all run on the same thread
Log.d(tag,"after send broadcast from main menu");
}
satya - Monday, May 24, 2010 1:24:01 PM
Here is a list of receivers in the manifest file to support this example
<receiver android:name=".TestReceiver">
<intent-filter>
<action android:name="com.ai.android.intents.testbc"/>
</intent-filter>
</receiver>
<receiver android:name=".TestTimeDelayReceiver">
<intent-filter>
<action android:name="com.ai.android.intents.testbc"/>
</intent-filter>
</receiver>
<receiver android:name=".TestReceiver2">
<intent-filter>
<action android:name="com.ai.android.intents.testbc"/>
</intent-filter>
</receiver>
Note again that a receiver is a child element of application at the same level as activity, service, or a provider. Also because they are all sub components of an application
In this example the broadcast action is: com.ai.android.intents.testbc
satya - Monday, May 24, 2010 1:25:18 PM
Source code for TestReceiver
public class TestReceiver extends BroadcastReceiver
{
private static final String tag = "TestReceiver";
@Override
public void onReceive(Context context, Intent intent)
{
Utils.logThreadSignature();
Log.d("TestReceiver", "intent=" + intent);
String message = intent.getStringExtra("message");
Log.d(tag, message);
}
}
satya - Monday, May 24, 2010 1:26:39 PM
Source code for TestTimeDelayReceiver
public class TestTimeDelayReceiver extends BroadcastReceiver
{
private static final String tag = "TestTimeDelayReceiver";
@Override
public void onReceive(Context context, Intent intent)
{
Utils.logThreadSignature();
Log.d(tag, "intent=" + intent);
Log.d(tag, "going to sleep for 2 secs");
Utils.sleepForInSecs(2);
Log.d(tag, "wake up");
String message = intent.getStringExtra("message");
Log.d(tag, message);
}
}
satya - Monday, May 24, 2010 1:27:54 PM
Source code for TestReceiver2
public class TestReceiver2 extends BroadcastReceiver
{
private static final String tag = "TestReceiver2";
@Override
public void onReceive(Context context, Intent intent)
{
Utils.logThreadSignature();
Log.d(tag, "intent=" + intent);
String message = intent.getStringExtra("message");
Log.d(tag, message);
}
}
satya - Monday, May 24, 2010 1:29:26 PM
Here is how I invoked the broadcast from a menu item
public boolean onOptionsItemSelected(MenuItem item)
{
.....
if (item.getItemId() == R.id.menu_send_broadcast)
{
this.testSendBroadcast();
return true;
}
....
}
satya - Monday, May 24, 2010 1:30:35 PM
Here is the supporting locat
//*******************************************************
//main thread
//6th sec, 457 msec
//before broadcast sent
//*******************************************************
05-24 17:06:06.457: DEBUG/ThreadUtils(345): main:(id)1:(priority)5:(group)main
//*******************************************************
//after broadcast sent
//as part of the menu
//see that this shows up first
//this proves the broadcast is queued for a later operation
//*******************************************************
05-24 17:06:06.517: DEBUG/HelloWorld(345): after send broadcast from main menu
//*******************************************************
//Message from TestReceiver: first one
//6th sec, 688 msec
//*******************************************************
05-24 17:06:06.688: DEBUG/ThreadUtils(345): main:(id)1:(priority)5:(group)main
05-24 17:06:06.727: DEBUG/TestReceiver(345): intent=Intent {
act=com.ai.android.intents.testbc
cmp=com.ai.android.bcr/.TestReceiver (has extras) }
05-24 17:06:06.737: DEBUG/TestReceiver(345): Hello world
//*******************************************************
//Message from TestTimeDelayReceiver: second receiver
//6th sec, 837 msec
//*******************************************************
05-24 17:06:06.837: DEBUG/ThreadUtils(345): main:(id)1:(priority)5:(group)main
05-24 17:06:06.857: DEBUG/TestTimeDelayReceiver(345): intent=Intent {
act=com.ai.android.intents.testbc
cmp=com.ai.android.bcr/.TestTimeDelayReceiver (has extras) }
//
//Go to sleep for 2 secs
//
05-24 17:06:06.908: DEBUG/TestTimeDelayReceiver(345): going to sleep for 2 secs
05-24 17:06:08.973: DEBUG/TestTimeDelayReceiver(345): wake up
//
//Notice the time
//8th sec, 207 msecs
//
05-24 17:06:09.207: DEBUG/TestTimeDelayReceiver(345): Hello world
//*******************************************************
//Message from TestReceiver2: the third receiver
//*******************************************************
05-24 17:06:09.287: DEBUG/ThreadUtils(345): main:(id)1:(priority)5:(group)main
05-24 17:06:09.297: DEBUG/TestReceiver2(345): intent=Intent {
act=com.ai.android.intents.testbc
cmp=com.ai.android.bcr/.TestReceiver2 (has extras) }
05-24 17:06:09.317: DEBUG/TestReceiver2(345): Hello world
satya - Monday, May 24, 2010 1:42:47 PM
Oh, here is the utils class that has the encapsulated thread functions
public class Utils
{
public static long getThreadId()
{
Thread t = Thread.currentThread();
return t.getId();
}
public static String getThreadSignature()
{
Thread t = Thread.currentThread();
long l = t.getId();
String name = t.getName();
long p = t.getPriority();
String gname = t.getThreadGroup().getName();
return (name
+ ":(id)" + l
+ ":(priority)" + p
+ ":(group)" + gname);
}
public static void logThreadSignature()
{
Log.d("ThreadUtils", getThreadSignature());
}
public static void sleepForInSecs(int secs)
{
try
{
Thread.sleep(secs * 1000);
}
catch(InterruptedException x)
{
throw new RuntimeException("interrupted",x);
}
}
}
satya - Tuesday, May 17, 2011 11:05:45 AM
starting an activity in broadcastreceiver android
starting an activity in broadcastreceiver android
Search for: starting an activity in broadcastreceiver android
satya - Tuesday, May 17, 2011 11:06:49 AM
Here is a discussion on this topic from developers group
satya - Tuesday, May 17, 2011 11:17:58 AM
Looks like this is allowed!!
Ideal way to send response to a user from a broadcast receiver is the notification manager. Otherwise it will be jarring if a user is working on an application and a new windows pops open.
But looks like this is possible if you were to use the flags
flag_activity_new_task flag_from_background flag_activity_singletop
satya - Tuesday, May 17, 2011 11:18:20 AM
flag_from_background
flag_from_background
Search Google for: flag_from_background
Search Android Developers Group for: flag_from_background
Search Android Beginers Group for: flag_from_background
satya - Tuesday, May 17, 2011 11:22:52 AM
Here is a lengthy discussion on how to start an activity from a service
Here is a lengthy discussion on how to start an activity from a service
satya - 5/2/2013 11:40:39 AM
Here is the doc reference on flag_from_background
Here is the doc reference on flag_from_background
it merely states the following
Can be set by the caller to indicate that this Intent is coming from a background operation, not from direct user interaction.
satya - 7/15/2014 12:40:04 PM
android broadcast receivers not getting invoked or called jellybean
android broadcast receivers not getting invoked or called jellybean
Search for: android broadcast receivers not getting invoked or called jellybean
satya - 7/15/2014 12:40:34 PM
Here is a lengthy discussion on the subject at SOF
satya - 7/15/2014 12:46:59 PM
activating android broadcast receivers
activating android broadcast receivers
satya - 7/15/2014 12:53:59 PM
Apparently you have to do this now
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
This will allow packages or applications that are in a stopped state to be invoked. Apparently this was introduced because of a security threat of some kind.
satya - 7/15/2014 12:54:10 PM
FLAG_INCLUDE_STOPPED_PACKAGES
FLAG_INCLUDE_STOPPED_PACKAGES
satya - 7/15/2014 1:36:08 PM
Here is more from Ashmita Adusumille
satya - 7/15/2014 1:38:48 PM
Launch controls on stopped applications: notes from 3.1, API 12
Launch controls on stopped applications: notes from 3.1, API 12
satya - 7/15/2014 1:47:04 PM
Here is the gist of it
Application when installed will be in a stopped state
Intents can now specify to target those applications that are only in started state. By default the old behavior persists.
However, for broadcast intents the system automatically adds a flag to exclude applications that are in stopped state
To overcome the previous point, one can explicitly set an intent flag on the broadcast intent to include those stopped applications as valid targets.
satya - 7/15/2014 1:49:05 PM
New class: LocalBroadcastManager
New class: LocalBroadcastManager
Helper to register for and send broadcasts of Intents to local objects within your process. This is has a number of advantages over sending global broadcasts with sendBroadcast(Intent):
You know that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.
It is not possible for other applications to send these broadcasts to your app, so you don't need to worry about having security holes they can exploit.
It is more efficient than sending a global broadcast through the system.
satya - 7/15/2014 1:50:27 PM
New class: WakefulBroadcastReceiver
New class: WakefulBroadcastReceiver
Helper for the common pattern of implementing a BroadcastReceiver that receives a device wakeup event and then passes the work off to a Service, while ensuring that the device does not go back to sleep during the transition.
This class takes care of creating and managing a partial wake lock for you; you must request the WAKE_LOCK permission to use it.
satya - 7/15/2014 1:54:48 PM
Newer facts about a BroadcastReceiver explicitly not covered here
Newer facts about a BroadcastReceiver explicitly not covered here
You can use the support library to optimize local receivers vs remote receivers
new flags are available to start stopped processes that have receivers in them
you have class that makes a broadcast receiver looks like a service. (This looks eerily similar to what I have documented in the Pro Android series earlier editions)
There is a way to conduct ordered broadcasts through sendOrderedBroadcast
there is a way to control security for both receivers and also senders.
There is a way to enable or disable receivers both in the manifest file and also programmatically
there is a way to indicate in the manifest file if a receiver is exported and available for use by external processes
Most of these details you can get it from the link above.
satya - 7/15/2014 2:58:40 PM
android boot_completed broadcast receiver not received
android boot_completed broadcast receiver not received
Search for: android boot_completed broadcast receiver not received
satya - 7/15/2014 3:10:11 PM
android application stopped state on install
android application stopped state on install
satya - 7/15/2014 3:12:07 PM
Here is a twist on stopped state and on device installation
satya - 7/15/2014 3:15:53 PM
Here is some source code/design documentation that is still not entirely clear
Here is some source code/design documentation that is still not entirely clear
satya - 7/15/2014 3:21:14 PM
Here is the crux of my question and I suspected
satya - 7/15/2014 3:24:20 PM
So here is the clarification I have been seeking
An app is in stopped state ONLY after install or a forced stop
it is not in stopped state if it is used even once, and even after any number of reboots after that! Then it is not that bad....
satya - 7/15/2014 3:26:42 PM
Also, applications installed on the /system partition are not subject to being placed into the "stopped" state after installation.
Also, applications installed on the /system partition are not subject to being placed into the "stopped" state after installation.