Showing posts with label notifications. Show all posts
Showing posts with label notifications. 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.


Monday, September 21, 2009

Service and Notification | Android Tutorial for Beginners – (Part 8)


Now that we have worked with services and notifications separately, we are all ready to use the two together to make a real service that is notified to the user through a status bar update that the service is running. The status bar removes the notification as soon as the service is stopped.


In this program, I also increment a counter once the service starts to show that the service is continuously running in the background while we do other work. When we stop the service we are able to see the updated count.


Let us look at the code:


I have created a class NotifyService which extends the service class. This is the service class that will be started through the activity – ServiceLauncher


Now let us see what the service does?


It does 3 things – Toast a message that the service has started. Update the status bar with a notification. Finally start incrementing the counter. All this is done in the onCreate() method of the NotifyService Class


Toast.makeText(this,"Service created at " + time.getTime(), Toast.LENGTH_LONG).show();
showNotification();          
            incrementCounter();


Here is theshowNotification() Method:


    private void showNotification() {
 CharSequence text = getText(R.string.service_started);
 Notification notification = new Notification(R.drawable.android, text, System.currentTimeMillis());
 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ServiceLauncher.class), 0);
notification.setLatestEventInfo(this, getText(R.string.service_label),
      text, contentIntent);
nm.notify(R.string.service_started, notification);
    }


Finally, here is the method for incrementing the counter incrementCounter():


    private void incrementCounter() {
timer.scheduleAtFixedRate(new TimerTask(){ public void run() {counter++;}}, 0, 1000L);
    }


On stopping the service, it obviously has to do the reverse actions: stop the counter, remove the status bar notification and then toast a message to the end user saying the service has stopped! So here it is:


      shutdownCounter();
      nm.cancel(R.string.service_started);
      Toast.makeText(this, "Service destroyed at " + time.getTime() + "; counter is at: " + counter, Toast.LENGTH_LONG).show();
      counter=null;


This is the code in the onDestroy()method in the NotifyServiceclass.


With this the service is ready. But we need to be able to start this service and stop it. This I have done through a ServiceLauncher class just as I had done in the previous part of this series. You can get the complete code here.

Thursday, September 3, 2009

Local Service | Android Tutorial for Beginners – (Part 7)


Service is a fundamental component in android. Many a time, applications will need to run processes for a long time without any intervention from the user, or very rare interventions. These background processes need to keep running even when the phone is being used for other activities / tasks.


To accommodate for such a requirement, android has introduced the “Service” component. It is a long lived component and does not implement any user interface of its own.


Typically a user interacts with a service through an activity that has a UI. The service by itself “notifies” the user in case of any need for user intervention.


In this article, I would like to introduce you to a very simple service which runs in the background but does not have any notification features.


In order to start and stop the service, I have created an activity called the service controller.


In my example, when the service starts, it toasts a message that the service has started. When the service ends, it toasts a message that the service has ended. This is not of much use in the real sense of services. However, it simplifies the introduction of service creation and destruction.


Ideally, one of the ways could be: a service that is running should notify itself as running by putting up a status bar notification as discussed in the previous article. And when the service has completed running the notification can be removed. Through the notification, the service can give a user interface for binding to the service or viewing the status of the service or any other similar interaction with the service. The combination of service with notification will be an example I will give in the next part.


Before we jump into the example, a little more about services.


Binding to a service:
Once a service has begun and is running in the background, any number of activities can “bind” to the service. In fact, if we want to bind to a service that has not started, calling to bind could initiate the service. Such a service would shut down as soon as the last user detaches from the service.


Remote service
The services defined above are those that run in the same process as the application that started it. However, we can have services that run in its own process. This is particularly useful when the service has to run for a long time, typical example being a background music player. For two processes to communicate, the object being passed needs to be marshaled.


For this, Android provides a AIDL tool (Android Interface Definition Language) to handle all marshalling and communication. The remote service example will be taken up in a subsequent article.


Service Example (code downloadable here)


Step 1:
Let us start with creating a service class that extends android.app.Service.
This service just displays a message when started and again displays a message when stopped. Hence the onStart()and onDestroy() methods are implemented. Here is the code.


public class SimpleService extends Service {
      @Override
      public IBinder onBind(Intent arg0) {
            return null;
      }
      @Override
      public void onCreate() {
            super.onCreate();
            Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
      }
     
      @Override
      public void onDestroy() {
            super.onDestroy();
            Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
      }
}


Step 2:
An entry for this service needs to be made in the AndroidManifest.xml file. Here it is:


            <service android:name=".SimpleService">
            </service>


Step 3:
Now, we need to be able to invoke this service. i.e. start the service and stop the service. I choose to write an activity that can start and stop the service. This activity is called SimpleServiceController.
Here is what it does:
To start the service –


              Button start = (Button)findViewById(R.id.serviceButton);
…
              start.setOnClickListener(startListener);
…
       private OnClickListener startListener = new OnClickListener() {
            public void onClick(View v){
startService(new Intent(SimpleServiceController.this,SimpleService.class));
            }                
       };


Similarly to stop the service –
              Button stop = (Button)findViewById(R.id.cancelButton);
…
              stop.setOnClickListener(stopListener);
…
       private OnClickListener stopListener = newOnClickListener() {
            public void onClick(View v){
stopService(new Intent(SimpleServiceController.this,SimpleService.class));
            }                
          };


Step 4:
The entry for this class in the AndroidManifest.xml file is as usual:
        <activity android:name=".SimpleServiceController"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>


Now we can launch this application and we can start and stop a service.

Wednesday, September 2, 2009

Notifications - Android Tutorial for Beginners (Part 6)


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 NotificationManagerbut 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 notificationobject. 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:


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


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


finalNotification 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 = new Intent(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.