How to use a broadcast receiver

How to use android broardcast receiver

Search for: How to use android broardcast receiver

Class documentation for BroadcastReceiver

NotificationManager

Search for: NotificationManager

See if there are any examples in samples

Some introductory notes on broadcast receiver usage

useful android broadcast intents

Search for: useful android broadcast intents

You can find standard broadcast intent actions here at this link for Intent class


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

A good one to test:ACTION_WALLPAPER_CHANGED

WallPaperManager

Search for: WallPaperManager

API samples has an example: AlarmController.java

You may want to understand how pending intents works: look here

How is a broadcast receiver configured in the manifest file?

Search for: How is a broadcast receiver configured in the manifest file?

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


<application>
   <receiver name="classname" ...>
        <intent-filter>

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

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

}

what does broadcastreceiver process attribute stand for?

Search for: what does broadcastreceiver process attribute stand for?

Perhaps we can look at AndroidManifestReceiver

AndroidManifestReceiver

Search for: AndroidManifestReceiver

The docs for the receiver element

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.

Why use a broadcastreceiver with explicit classname at all?

Search for: Why use a broadcastreceiver with explicit classname at all?

default is true, and if false this receiver will not be instantiated.

why allow broadcastreceiver without intent filters?

Search for: why allow broadcastreceiver without intent filters?

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

the sender must have this permissions to send to this receiver. If not specified open to all

Read security subject

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 element's process attribute can set a different default for all components. But each component can override the default with its own process attribute, allowing you to spread your application across multiple processes.

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.

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

Does a broadcast receiver execute in the main thread

Search for: Does a broadcast receiver execute in the main thread

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

The following is a meaty thread to read on this subject

I will report the findings in a lil while

Read this note on responsiveness and what happens to threads

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.

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.

See if this source code link works

common tasks note on broadcast receivers


// 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);

<receiver class=".AlarmReceiver" />

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

Use this link to discover telephony events

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

This link below seem to suggest that broadcast receivers do run in the main ui thread

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

A BroadcastReceiver hasn't finished executing within 10 seconds


Activity Manager
Window Manager

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

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.

your main thread should provide a Handler for child threads to post back to upon completion.

5 second input event timeout

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.

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

why would I use sendBroadcast with explicit classname?

Search for: why would I use sendBroadcast with explicit classname?

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");
}

<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


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

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

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

public boolean onOptionsItemSelected(MenuItem item) 
{
   .....
   if (item.getItemId() == R.id.menu_send_broadcast)
   {
      this.testSendBroadcast();
      return true;
   }
   ....
}

//*******************************************************
//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

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

starting an activity in broadcastreceiver android

Search for: starting an activity in broadcastreceiver android

Here is a discussion on this topic from developers group

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

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

Search Google Code for: flag_from_background

Search Android Issues Database for: flag_from_background

Here is a lengthy discussion on how to start an activity from a service

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.

android broadcast receivers not getting invoked or called jellybean

Search for: android broadcast receivers not getting invoked or called jellybean

Here is a lengthy discussion on the subject at SOF

activating android broadcast receivers

Search for: activating android broadcast receivers

Here is more discussion


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.

FLAG_INCLUDE_STOPPED_PACKAGES

Search for: FLAG_INCLUDE_STOPPED_PACKAGES

Here is more from Ashmita Adusumille

Launch controls on stopped applications: notes from 3.1, API 12

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.

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.

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.

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.

android boot_completed broadcast receiver not received

Search for: android boot_completed broadcast receiver not received

Here is the issue submitted

android application stopped state on install

Search for: android application stopped state on install

Here is a twist on stopped state and on device installation

Here is some source code/design documentation that is still not entirely clear

Here is the crux of my question and I suspected

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

Also, applications installed on the /system partition are not subject to being placed into the "stopped" state after installation.

Search for: Also, applications installed on the /system partition are not subject to being placed into the "stopped" state after installation.

Closest reference to this is here