Mostrando entradas con la etiqueta Android Tutorial. Mostrar todas las entradas
Mostrando entradas con la etiqueta Android Tutorial. Mostrar todas las entradas

jueves, 15 de marzo de 2012

Android Tutorial for Beginners | Notifications |


We have seen Activities and Intents. Now we need to move on to services. However, since services mostly interact with a user through notifications, I felt the need to introduce a simple program to deal with Notifications. 

What are Notifications? The name itself implies their functionality. They are a way of alerting a user about an event that he needs to be informed about or even take some action on getting that information. 

Notification on Android can be done in any of the following ways:
  • ·         Status Bar Notification
  • ·         Vibrate
  • ·         Flash lights
  • ·         Play a sound

From the Notification, you can allow the user to launch a new activity as well. Now we will look at status bar notification as this can be easily tested on the emulator.

To create a status bar notification, you will need to use two classes: Notification and NotificationManager.
  • ·         Notification – defines the properties of the status bar notification like the icon to display, the test to display when the notification first appears on the status bar and the time to display.
  • ·         NotificationManager is an android system service that executes and manages all notifications. Hence you cannot create an instance of the NotificationManager but you can retrieve a reference to it by calling the getSystemService() method.

Once you procure this handle, you invoke the notify() method on it by passing the notification object created. 

So far, you have all the information to display on the status bar. However, when the user clicks the notification icon on the status bar, what detailed information should you show the user? This is yet to be created. This is done by calling the method setLatestEventInfo() on the notification object. What needs to be passed to this method, we will see with an example.

You can download the code for a very simple Notification example here:

The code is explained below:

Step 1: Procure a handle to the NotificationManager:

            private NotificationManager mNotificationManager;
      …
mNotificationManager = 
      (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

Step 2: Create a notification object along with properties to display on the status bar

final Notification notifyDetails =
new Notification(R.drawable.android,"New Alert, Click Me!",System.currentTimeMillis());

Step 3: Add the details that need to get displayed when the user clicks on the notification. In this case, I have created an intent to invoke the browser to show the website http://www.android.com 

Context context = getApplicationContext();
      
CharSequence contentTitle = "Notification Details...";
      
CharSequence contentText = "Browse Android Official Site by clicking me";
Intent notifyIntent = newIntent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
      
PendingIntent intent = 
      PendingIntent.getActivity(SimpleNotification.this, 0, 
      notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
Step 4: Now the stage is set. Notify. 
       
      mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);

Note that all of the above actions(except getting a handle to the NotificationManager) are done on the click of a button “Start Notification”. So all the details go into the setOnClickListener() method of the button.
Similarly, the notification, for the example sake is stopped by clicking a cancel notification button. And the code there is :
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);

Now, you may realize that the constant SIMPLE_NOTIFICATION_ID becomes the way of controlling, updating, stopping a current notification that is started with the same ID.

For more options like canceling the notification once the user clicks on the notification or to ensure that it does not get cleared on clicking the “Clear notifications” button, please see the android reference documentation. 

lunes, 12 de marzo de 2012

Android Tutorial for Beginners | Implicit Intents |


We have seen before, how to use Explicit Intents to invoke activities through a very simple example. Now, we will move on to a more interesting concept of Implicit Intents and Intent Filters. 

This requires a little of theoretical understanding before we move on to an example. 

As described earlier, an implicit intent does not name a target component that should act upon the intent. I 
also said that the android platform resolves as to which component is best suited to respond to an Implicit Intent. How does this happen?

Basically, an Intent object has the following information (among other things like Component name, extras and flags) which is of interest for implicit intents:
  • Action 
  • Category 
  • Data 
So, the android platform compares these 3 (action, category and data) to something called "Intent Filters" that are declared by probable target components who are willing to accept Implicit Intent calls.
i.e. Intent Filters are the way of any component to advertise its own capabilities to the Android system. This is done declaratively in the AndroidManifest.xml file.

So here are some important points to remember:
  1. Implicit Intents do not specify a target component 
  2. Components willing to receive implicit intents have to declare their ability to handle a specific intent by declaring intent filters 
  3. A component can declare any number of Intent Filters 
  4. There can be more than one component that declares the same Intent Filters and hence can respond to the same implicit intent. In that case the user is presented both the component options and he can choose which one he wants to continue with 
  5. You can set priorities for the intent filters to ensure the order of responses. 
There are 3 tests conducted in order to match an intent with intent filters:
  1. Action Test 
  2. Category Test 
  3. Data Test 
For more details about them, you may visit the Android developer documentation here.

Finally we shall look at declaring an implicit intent in one activity which will invoke one of the native activities of the platform by matching the intent filters declared by the same.

The complete code for a very simple implicit intent example that has been described in this article is available for download here.

The InvokeImplicitIntent Activity creates an implicit intent object "contacts". This intent object's component is not set. However, the action is set to "android.content.intent.ACTION_VIEW" and the data's URI is set to "People.CONTENT_URI". 

Such an intent matches with the intent filter declared by the view contacts native activity.
So, when you run this application, it displays the native UI for viewing the existing contacts on the phone!

Here is the relevant piece of code for the same:
           Button viewContacts = (Button)findViewById(R.id.ViewContacts);
        
            viewContacts.setOnClickListener(new OnClickListener() {
            
             public void onClick(View v) {
              Intent contacts = new Intent();
              contacts.setAction(android.content.Intent.ACTION_VIEW);
              contacts.setData(ContactsContract.Contacts.CONTENT_URI);
              startActivity(contacts);
             }
            });

In this manner many of the native applications can be seamlessly invoked as one of the activities in our applications through implicit intents.

Here is the complete source code that has been tested with Android SDK 2.1