Ad

Showing posts with label Broadcast Receiver. Show all posts
Showing posts with label Broadcast Receiver. Show all posts

Tuesday, October 6, 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.BroadcastReceiverclass 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.


Tuesday, August 25, 2009

Fundamentals | Android Tutorial for Beginners (Part 1)

This is Part 1 of a series of articles I plan to write to simplify the new paradigms introduced by the Android platform for developers.
The part 1 will only define and introduce the fundamental building blocks of Android. Later articles will provide sample code focusing on one aspect at a time, more to drive home to concept than to show any great programming skills.


From a developer's perspective, the fundamental building blocks / components of Android are:
1. Activities
2. Services
3. Broadcast Receivers
4. Content Providers.


The means of communication between the above mentioned components is through
1. Intents
2. Intent Filters


The User Interface elements are by using what are called:
1. Views
2. Notifications


Now, having broadly classified the basics, I would like to give a simple definition for each of them, before we can appreciate the need for each of them.


Activity is the basic building block of every visible android application. It provides the means to render a UI. Every screen in an application is an activity by itself. Though they work together to present an application sequence, each activity is an independent entity.


Service is another building block of android applications which does not provide a UI. It is a program that can run in the background for an indefinite period.


Broadcast Receiver is yet another type of component that can receive and respond to any broadcast announcements.


Content Providers are a separate league of components that expose a specific set of data to applications.


While the understanding and knowledge of these four components is good enough to start development, the knowledge of the means of communication between the components is also essential. The platform designers have introduced a new conpect of communication through intents and intent filters.


Intents are messages that are passed between components. So, is it equivalent to parameters passed to API calls? Yes, it is close to that. However, the fundamental differences between API calls and intents' way of invoking components is
1. API calls are synchronous while intent-based invocation is asynchronous (mostly)
2. API calls are bound at compile time while intent-based calls are run-time bound (mostly)


It is these two differences that take Android platform to a different league.


NOTE: Intents can be made to work exactly like API calls by using what are called explicit intents, which will be explained later. But more often than not, implicit intents are the way to go and that is what is explained here.



One component that wants to invoke another has to only express its' "intent" to do a job. And any other component that exists and has claimed that it can do such a job through "intent-filters", is invoked by the android platform to accomplish the job. This means, both the components are not aware of each other's existence and can still work together to give the desired result for the end-user.


This dotted line connection between components is achieved through the combination of intents, intent-filters and the android platform.


This leads to huge possibilities like:
1. Mix and match or rather plug and play of components at runtime
2. Replacing the inbuilt android applications with custom developed applications
3. Component level reuse within and across applications
4. Service orientation to the most granular level, if I may say


Now that the concept of intent has been introduced, let me get down to a more formal definition of Intent.


Intent is a bundle of information, a passive data structure that holds an abstract description of the operation to be performed. (or in the case of broadcasts, a description of an event that has happened and is being announced).


There are 2 types of intents which I intend to detail in the next part of this series. Before winding up part 1, I would finally also give you a formal definition of Intent filters.


Intent filters are the means through which a component advertizes its own capabilities to handle specific job/operations to the android platform.