Quick Android Notification Example

So we all know and love our Android notification bar. So I just wanted to post a quick example application to show how easy it is to display a local notification.

The process runs something like this:

  • retrieve a reference to the NotificationManager
  • create a Notification
  • notify the manager of the notification you've created

The Notification class, at it's simplest consists of an image icon and 3 pieces of text, one for the ticker, one as the title and the last as the content text.

  1. package com.distriqt.mobile.experiments;
  2.  
  3. import android.app.Activity;
  4. import android.app.Notification;
  5. import android.app.NotificationManager;
  6. import android.app.PendingIntent;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.os.Bundle;
  10.  
  11. public class NotificationExperimentActivity extends Activity
  12. {
  13. private static final int HELLO_ID = 1;
  14.  
  15. @Override
  16. public void onCreate(Bundle savedInstanceState)
  17. {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.main);
  20.  
  21. //
  22. // Look up the notification manager server
  23. NotificationManager nm =
  24. (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  25.  
  26. //
  27. // Create your notification
  28. int icon = R.drawable.icon;
  29. CharSequence tickerText = "Hello";
  30. long when = System.currentTimeMillis();
  31.  
  32. Notification notification =
  33. new Notification( icon, tickerText, when);
  34.  
  35. Context context = getApplicationContext();
  36. CharSequence contentTitle = "My notification";
  37. CharSequence contentText = "Hello World!";
  38. Intent notificationIntent =
  39. new Intent(this, NotificationExperimentIntent.class);
  40. PendingIntent contentIntent =
  41. PendingIntent.getActivity(this, 0, notificationIntent, 0);
  42.  
  43. notification.setLatestEventInfo(
  44. context,
  45. contentTitle,
  46. contentText,
  47. contentIntent);
  48.  
  49. //
  50. // Send the notification
  51. nm.notify( HELLO_ID, notification );
  52. }
  53. }
  54.  

The Android developer documentation goes through all of this in detail here.

Published by

Michael

http://michaelarchbold.com

2 thoughts on “Quick Android Notification Example”

Leave a Reply

Your email address will not be published. Required fields are marked *