×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: joseifm
Added: Sep 23, 2014 4:31 PM
Modified: Sep 23, 2014 4:37 PM
Views: 22
Display Notification in Status Bar Android
  1. import android.app.Notification;
  2. import android.app.NotificationManager;
  3. import android.app.PendingIntent;
  4.  
  5. int notificationID = 1;
  6. displayNotification("text_to_show");
  7.  
  8. protected void displayNotification(String text_to_show){
  9.  
  10. //Change MyActivity.class with your activity.class to receive the action of notification
  11.         Intent i = new Intent(this, MyActivity.class);
  12.         i.putExtra("notificationID", notificationID);
  13.  
  14.         PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);
  15.         NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  16.  
  17.         CharSequence ticker ="Text on Status Bar";
  18.         CharSequence contentTitle = "Title text";
  19.         CharSequence contentText = "Menssage to show";
  20.         Notification noti = new NotificationCompat.Builder(this)
  21.                 .setContentIntent(pendingIntent)
  22.                 .setTicker(ticker)
  23.                 .setContentTitle(contentTitle)
  24.                 .setContentText(contentText)
  25.                 .setSmallIcon(R.drawable.ic_launcher)
  26.                 .addAction(R.drawable.ic_launcher, ticker, pendingIntent)
  27.                 .setVibrate(new long[] {100, 250, 100, 500})
  28.                 .build();
  29.         nm.notify(notificationID, noti);
  30. //Add permission to vibrate in file AndroidManifest.xml
  31. //<uses-permission android:name="android.permission.VIBRATE" />
  32.     }
  33.  
  34. // Cancel Notification on activity itself
  35.         NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  36. try {
  37.             nm.cancel(getIntent().getExtras().getInt("notificationID"));
  38.         }catch (java.lang.RuntimeException e){
  39.            
  40.         }