NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

x

Wednesday 7 October 2009

Broadcast Receivers | Android Developer Tutorial (Part 11)


The concept of Broadcast Receivers, one of the fundamental blocks of Android, is very simple. These are applications that will respond to any intent that is broadcast by other applications. Provided the broadcast intent matches the intent specified against the receiver in the AndroidManifest.xml


This goes to automatically imply that many activities, events, services or the like can broadcast intents expecting the appropriate action to be automatically taken. So, to begin with, let us see the various Broadcast events that are given by the platform itself. Here is a standard list obtained from the android documentation:


·         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


For details on when each of these intents get broadcasted, please see the android documentation. I have chosen the BROADCAST event ACTION_TIME_CHANGED as I can simulate a time change in the emulator. How to simulate the time change from adb shell is given at the end of this tutorial.


Now let us get on to the example of a broadcast receiver. You can download the complete code here.


Any activity that intends to respond to broadcasts has to extend the android.content.BroadcastReceiver class and implement the single method onReceive().


In my example, I just notify on the status bar that the time has changed and the moment the user clicks on the status bar and sees the details, clicks on the details, the notification is removed from the status bar.


When the user clicks on the detailed portion, I take the user to the contacts application, just for anything better. Ideally this should take to an activity relevant to the application. So, if you see the onReceive() method, it is nothing but a notification example. That is all.


      private NotificationManager mNotificationManager;
      private int SIMPLE_NOTFICATION_ID;
     
      @Override
      public void onReceive(Context context, Intent intent) {

        mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
      Notification notifyDetails = new Notification(R.drawable.android,"Time Reset!",System.currentTimeMillis());
      PendingIntent myIntent = PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_VIEW, People.CONTENT_URI), 0);
      notifyDetails.setLatestEventInfo(context, "Time has been Reset", "Click on me to view Contacts", myIntent);
      notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
      mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
            Log.i(getClass().getSimpleName(),"Sucessfully Changed Time");

      }


Once this class is ready, start the android emulator in eclipse. Then, simulate a time changed from the command prompt as given below. You will see the notification come up.


Simulating a time change in the emulator:


To start the adb shell type (in windows, assuming the path has been set to the tools folder of android sdk installation):


C:\> adb shell
#date –- 2009-10-01 14:24:59
20070325.123456
#date –s 20070325.123456


The first step date –- gives the time in seconds since Jan 1st 1970. Take the result and give it as a parameter to date –s, the time is reset in adb and within a minute on the android emulator. This broadcasts the event that time has been changed in the emulator and kicks off the Broadcast Receiver program that has been executed.


35 comments:

  1. Hi.

    is der anyway to know when a message has been sent from the phone...(lyk when i type in a message and at d moment i clik the send button i hav to catch som sort of notification...)
    Is it possible using Broadcast Receivers..????

    ReplyDelete
  2. Unfortunately there is (currently) no way to implement a BroadcastReceiver because the standard sms application uses a SmsManager to send the messages but specifies concrete internal classes for the sent and delivered intents (SmsReceiver.class and MessageStatusReceiver.class respectively). Not that it is any consolation but you can find the following comment in the Sms application's source:

    // TODO: Fix: It should not be necessary to
    // specify the class in this intent. Doing that
    // unnecessarily limits customizability.

    The best alternative seems to be polling content://sms/sent, potentially using a ContentObserver.

    ReplyDelete
  3. Hi,
    I have a problem and and i was hoping you could help me out with it.
    I have a broadcast receiver in one application which i would like to be used by another application? Is this possible and if yes how to do it??

    ReplyDelete
  4. Hi,
    can you please explain the difference between the APIs sendStickyBroadcast() and sendBroadcast.. I went the the android documentation and did not understand most of it.
    Hope you will help me..

    Thanks,
    Jins

    ReplyDelete
  5. Hi Jins,

    It is a very simple difference between setBroadcast() and sendStickyBroadcast(). The latter broadcasts an intent that will be available for receiviers at any point of time later then the broadcast itself.
    Support a sendStickyBroadcast() was done at 10:00 am this morning with an intent A, at 11:00 am, some other application registers for the broadcast intent A though the registerReceiver() method, it will receive the data braodcasted at 10:00 am also.
    Where as if it is not sticky, the receiver at a later time would not have received it.
    Hope this helps.

    ReplyDelete
  6. I have been reading and testing some of your demos and they have been very helpful. Great Job.
    I am new to android to so bear with me.
    I want to create a program that gets trigged when there is an incoming call. if I write it using the activity class , There is a change that android memory management system may kill my application while in the background.
    I am thinking now that the best way to achieve this is through a broadcast receiver. can you give me some pointer on this issue?
    Thanks

    ReplyDelete
  7. since my posting, I have figured out a way to to trigger the broadcast receiver by declaring a receiver and intent as "android.intent.action.PHONE_STATE" in the manifiest file.

    but it looks like the receiver get triggered every time there is any change in the state of the phone.
    is there a way I can set the intent to only trigger the receiver when there is incoming call?
    I can make my current situation work but it just seems
    waste of resources to trigger the receiver at any change of the phone.
    thanks

    ReplyDelete
  8. I have been reading some of your demos, its very helpful. Great Job.
    I am new to android to so bear with me.

    what is the difference between Register receiver and unregister receiver

    ReplyDelete
  9. Response to
    juan lee said...
    since my posting, I have figured out a way to to trigger the broadcast receiver by declaring a receiver and intent as "android.intent.action.PHONE_STATE" in the manifiest file.

    but it looks like the receiver get triggered every time there is any change in the state of the phone.
    is there a way I can set the intent to only trigger the receiver when there is incoming call?
    I can make my current situation work but it just seems
    waste of resources to trigger the receiver at any change of the phone.
    thanks





    // TODO: Consider sending out a serialized broadcast Intent here
    // (maybe "ACTION_NEW_INCOMING_CALL"), *before* starting the
    // ringer and going to the in-call UI. The intent should contain
    // the caller-id info for the current connection, and say whether
    // it would be a "call waiting" call or a regular ringing call.
    // If anybody consumed the broadcast, we'd bail out without
    // ringing or bringing up the in-call UI.
    //
    // This would give 3rd party apps a chance to listen for (and
    // intercept) new ringing connections. An app could reject the
    // incoming call by consuming the broadcast and doing nothing, or
    // it could "pick up" the call (without any action by the user!)
    // by firing off an ACTION_ANSWER intent.
    //
    // We'd need to protect this with a new "intercept incoming calls"
    // system permission.

    ReplyDelete
  10. Hi..

    Can you help me to call one application from another application in android.

    ReplyDelete
  11. I want to receive broadcast when particular application is launched means camera or music etc....I tried package_added and vending.install_referrer.
    Plz help

    ReplyDelete
  12. Hi Geetha !

    It's nice to see some-one working and sharing android issues.

    I have a similar prblm as that of Juan Lee..I have to listen for incoming phone calls ( even when the activity is in the background) but I am unable to find a working method that helps to register a broadcast receiver inside a service class. If I can register and do the onReceive() in the activity class only, then how will I ensure that it continues to receive even when the application is paused.

    ReplyDelete
  13. Hi Shipra...

    u can use


    it worked for me....you can receive when an incoming call received..

    ReplyDelete
  14. Hi Shipra...

    u can use
    android:name="android.intent.action.PHONE_STATE"

    it worked for me....you can receive when an incoming call received..

    ReplyDelete
  15. Hi!

    Thanks for the tutorial! But i would like to ask, what is PendingIntent exatly?

    ReplyDelete
  16. Hi,I found your blog very interesting.I am working on similar lines but I want my broadcast receiver to receive when the outgoing call is made.Can I do that..? please help me

    ReplyDelete
  17. hi, is there any way to get duration of ongoing call.

    ReplyDelete
  18. I trying to make an application to such as sending sms via handset and then converting that sms to email and vice-versa. i have come up with a design and till now i was going well. I am stuck across broadcastreciever.
    How sud i implement it because i only one to use a single broadcastreciever for multiple actions.
    For example if someone sms with apple, then i want the whole list of apples avialable and if the other sms is apple 1 info then i want to use the same broadcastreciever for fetching info of apple 1.
    Any idea

    ReplyDelete
  19. Hi is there a way to figure out if the user has manually changed the time from the automatic time from the network? Or is there an API which can be used to figure out network time?

    ReplyDelete
  20. Hi Geetha,

    I have a question. I work with some data structures in a service and when I want to end the service, I would like to take a backup of the data structure in my xml file of my format, so that on starting the service again, i can populate them again. For this I created a new activity in OnDestroy() of this service which would have access to this data structure and then complete the task and finish() itself. But problem is activity is generated but by the time the service has exited and data structure is no longer available to access. I understand since the lifetime of service ended, its data structures also are gone but is there a way I can achieve this? Basically until the last child finishes, all relevant data of the application should be available...Thanks in advance.

    ReplyDelete
  21. whts the actual use of pending intent in broadcast receiver or a message sending application.aslo how to put the pending intent in our application

    ReplyDelete
  22. mam how can i provide intent from newmsg to contacts im a IVB.E please help me

    ReplyDelete
  23. hi,its nice to see such a blog to clarify our doubts.
    can u tel me how to stop an outgoing call(single). i know through BroadCastReceiver->onreceive(). bt in onreceive i want to get phone number of an outgoing.how? which statement that i need to put to hold String NUMBE=?

    ReplyDelete
  24. Mam ,
    i just need to know what should be used in manifest file to track the browser details,, in side intent filter,,??

    ReplyDelete
  25. Mam,

    I want to create multiple Alarm Manager,in one class..I already try for that...but only last Alarm which has max time,is work..



    Please Tell me how should I use multiple Alarm Manager in one class.

    Thanks in advance

    Shailesh(shailesh.v88@gmail.com)

    ReplyDelete
  26. Hi,
    I want to get notified when there is any change in contacts. If any changes(insertion,deletion or any modification) are done, then display the modified or added contacts only.

    Please Help me. Thanks in Advance

    ReplyDelete
  27. Hi sai geetha...
    I have a problem with my android app notifications.My problem is if i have wifi in my mobile my service getting started perfectly and i'm getting notifications.If i'm with mobile network(Edge) also my service getting started perfectly.But some situations like i have network plan and i don't have balance in my mobile and my pocket data plan validity is over at that time my service giving some problems..and getting anr exception because service was getting stopped while network is in blinking but not connecting....please help me to get out this issue..

    ReplyDelete
  28. Hi sai Geetha..
    I have a problem with notification Services plz can u help.I have implemented Push Notifications using C2DM services provided by Google in my Application and if the notification arrives from the server i want to Reload Data from the Server , how can i do it.

    ReplyDelete
  29. HI, Sai Geetha,

    I want to start my application or precisely activity as soon as a USB is connected to the device. How to do that?
    I mean if I implement a broadcast receiver for USB than I need my app to be running always which I don't want. Even if that is possible I will have to start my app at the start up of device so how to do that.

    Any help is appreciated :)

    ReplyDelete
  30. hi ,
    i really thank full to you to understand the concept in easy and simple way

    ReplyDelete
  31. Is it possible to create a custom Broadcast Reciever for custom certain action..

    Thanks in Advance.
    Ashraf

    ReplyDelete
  32. Go through the below link to know about how to create custom Broadcast receiver for activities?
    http://android.programmerguru.com/android-broadcast-receiver-example/

    ReplyDelete
  33. Hi mam,

    I am using ACTION_TIME_CHANGED Broadcast action to get notified when user changes Date/Time in settings. It is working fine but sometimes Platform is broadcasting ACTION_TIME_CHANGED Action though it was not set by user.

    Can you please suggest me how to handle this.

    Thanks

    ReplyDelete