such as when email has been received. Moreover, the service may need some way to steer the user to an activity where they can act upon the event — reading a received message, for example. For this, Android supplies status- bar icons, flashing lights, and other indicators collectively known as notifications.

Your current phone may well have such icons, to indicate battery life, signal strength, whether Bluetooth is enabled, and the like. With Android, applications can add their own status-bar icons, with an eye towards having them appear only when needed (e.g., when a message has arrived).

In Android, you can raise notifications via the NotificationManager. The NotificationManager is a system service. To use it, you need to get the service object via getSystemService(NOTIFICATION_SERVICE) from your activity. The NotificationManager gives you three methods: one to pester (notify()) and two to stop pestering (cancel() and cancelAll()).

The notify() method takes a Notification, which is a data structure that spells out what form your pestering should take. The following sections describe all the public fields at your disposal (but bear in mind that not all devices will necessarily support all of these).

Hardware Notifications

You can flash LEDs on the device by setting lights to true, also specifying the color (as an #ARGB value in ledARGB) and what pattern the light should blink in (by providing off/on durations in milliseconds for the light via ledOnMS and ledOffMS).

You can play a sound, using a Uri to a piece of content held, perhaps, by a ContentManager(sound). Think of this as a ringtone for your application.

You can vibrate the device, controlled via a long[] indicating the on/off patterns (in milliseconds) for the vibration (vibrate). You might do this by default, or you might make it an option the user can choose when circumstances require a more subtle notification than an actual ringtone.

Icons

While the flashing lights, sounds, and vibrations are aimed at getting somebody to look at the device, icons are designed to take them the next step and tell them what’s so important.

To set up an icon for a Notification, you need to set two public fields: icon, where you provide the identifier of a Drawable resource representing the icon, and contentIntent, where you supply a PendingIntent to be raised when the icon is clicked. You should be sure the PendingIntent will be caught by something, perhaps your own application code, to take appropriate steps to let the user deal with the event triggering the notification.

You can also supply a text blurb to appear when the icon is put on the status bar (tickerText).

If you want all three, the simpler approach is to call setLatestEventInfo(), which wraps all three of those in a single call.

Seeing Pestering in Action

Let us now take a peek at the Notifications/Notify1 sample project (available in the Source Code section at http://apress.com), in particular the NotifyDemo class:

public class NotifyDemo extends Activity {

 private static final int NOTIFY_ME_ID = 1337;

 private Timer timer = new Timer();

 private int count = 0;

 @Override

 public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  Button btn = (Button)findViewById(R.id.notify);

  btn.setOnClickListener(new View.OnClickListener() {

   public void onClick(View view) {

    TimerTask task = new TimerTask() {

     public void run() {

      notifyMe();

     }

    };

    timer.schedule(task, 5000);

   }

  });

  btn = (Button)findViewById(R.id.cancel);

  btn.setOnClickListener(new View.OnClickListener() {

   public void onClick(View view) {

    NotificationManager mgr =

    (NotificationManager)getSystemService (NOTIFICATION_SERVICE);

    mgr.cancel(NOTIFY_ME_ID);

   }

  });

 }

 private void notifyMe() {

  final NotificationManager mgr =

   (NotificationManager)getSystemService (NOTIFICATION_SERVICE);

  Notification note = new Notification(R.drawable.red_ball,

   'Status message!', System.currentTimeMillis());

  PendingIntent i = PendingIntent.getActivity(this, 0,

Вы читаете Beginning Android
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату