Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Using Hardware Indicators with the Android SDK

by

In this Android quick tip you will learn about two new methods of alerting users to events: Vibration and LED/Trackball lighting. These methods are referred to as "Hardware Indicators," and are used sparingly in various Android apps to convey urgent information or breaking news. This article ties in closely with Android SDK: Using Alerts, Toasts and Notifications.

Vibrating the Device

Vibrations are controlled by a dedicated system-level service: the Vibrator Service. However, in order to use this service, your application must request the VIBRATE permission that has to be first declared in AndroidManifest.xml, like so (line 5):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example">

    <uses-permission android:name="android.permission.VIBRATE"/>

    <application android:label="HardwareIndicators">

        <activity android:name=".Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

First off, create an instance of Vibrator by invoking getSystemService():

     Vibrator vibr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

Now you can begin using the object's methods. There are three in total:

  • vibrate (long time)

    Vibrate for a specified duration (in milliseconds).

  • vibrate(long[] pattern, int repeat)

    Vibrate using the specified pattern and optionally repeat (explained below).

  • cancel()

    Cancel current vibrations.

Regarding vibrate(long[] pattern, int repeat): You have to pass an on-off pattern in form of a long[] array. First value indicates how long to wait, then how long to vibrate, and so on. The repeat parameter can be either "-1" if you don't want it to repeat or the index of the pattern array at which to repeat. If you do want it to repeat, then don't forget to cancel it eventually to prevent repeating indefinitely.

The example below illustrates the use of both vibrate() methods:

     Vibrator vibr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

     vibr.vibrate(500); // Vibrate for half a second (500 milli seconds)

     long[] pattern = {400, 200};
     vibr.vibrate(pattern, 0); // 400ms pause, 200ms vibration. Start repeating at index 0.

Typically, vibrations are associated with receiving a phone call or some other important system notification that users expect. Vibrations demand attention from users. Even if the user's phone is on standby or they have it pocketed, vibrations are a type of notification that have the greatest guarantee that users will take note of something and will want to check their phone to find out what's happening. You definitely do not want busy individuals being annoyed by a random alert every few minutes, as chances are they will most likely end up removing the app entirely!

When and how should you make use of vibrations? The simple answer: only if it contributes to a better user experience. Even then, it's a good practice to offer some sort of settings panel that allows users to disable it from being used in your application. An example of an appropriate use of this service would be a calendar app that notifies the user of an upcoming event.

In summary, only use vibrations for appropriate purposes. Don't overuse them and keep them fairly short unless the application requires immediate attention.

Lighting up a Hardware LED/Trackball with Android Notifications

Start off with an instance of NotificationManager, another core system service:

       NotificationManager notifMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Next, construct a new Notification object:

  Notification notif = new Notification();
  notif.ledARGB = Color.argb(255, 0, 255, 0);
  notif.flags |= Notification.FLAG_SHOW_LIGHTS;
  notif.ledOnMS = 200;
  notif.ledOffMS = 300;

ledARGB is used to specify an alpha, red, green and blue color value combined into one single integer. android.graphics.Color's handy argb() method is the easiest way to produce it. In the example above, it spits out red with full intensity (255 for Red and 255 for Alpha). You can, of course, simply use one of the Color class' constants such as Color.RED.

flags has the FLAG_SHOW_LIGHTS flag added to it via a bitwise operation. It simply indicates that you want to make use of a device's LED in this notification object.

ledOnMS and ledOffMS: The LED will flash with ledOnMS denoting how long the LED will be on and ledOffMS indicating how long it should stay off between flashes. The code below demonstrates this:

    // Flashes LED on and off. (Times in milliseconds)
    notif.ledOnMS = 1000;
    notif.ledOffMS = 300;

    // Turns LED on. Setting it like this will result in a default pause between flashes, which lasts around 2 seconds.
    notif.ledOnMS = 1;
    notif.ledOffMS = 0;

Lastly, call notify(int id, Notification) and pass the Notification object we created and configured. For now, it should be okay to give it a random value as an ID, but keep track of it so you can cancel the notification later on. The better method is to store it in a constant rather than hard-coding the number as a parameter, but this is an educational tutorial, so we will simply hard code it for demonstration purposes.

    notifMgr.notify(1234, notif);

Now, what does this result in? The LED will only start flashing if your screen is off and it'll stop when you turn it back on or call cancel(). This is how the Android notification system was designed; there is currently no way to take direct control of LED/trackball lighting. Also, do keep in mind that you have to call notifMgr.cancel(1234) eventually - 1234 being the ID that you specified earlier. You could setup a timer to take care of that or you could invoke it when your activity regains focus.

I'm going to round this post up with a few words on compatibility: every device line differs in some way. Some phones have a trackball with lighting capabilities, others have an LED, and some have neither. The Android system will do its best in an attempt to do what you've told it to, but it can't make any guarantees.

Conclusion

Always remember: Use any type of alert sparingly and wisely. It is better to err on the safe side and decide against using vibrations/lights than to overuse them, thus annoying users which could result in a poor end-user experience. Finally, if you've been following along and want to test the tutorial's code, you're going to have to use a real Android device, as the emulator supports neither vibrations nor LEDs. For now, the simulator unfortunately won't show a friendly "LED is currently flashing!" popup. Maybe it will in future. . .I certainly hope so.

Advertisement