Skip to content

Instantly share code, notes, and snippets.

@izmajlowiczl
Created May 29, 2013 09:47
Show Gist options
  • Save izmajlowiczl/5669185 to your computer and use it in GitHub Desktop.
Save izmajlowiczl/5669185 to your computer and use it in GitHub Desktop.
Android Show Notification with NotificationCompat
createNotification(Calendar.getInstance().getTimeInMillis(), "hey!");
public static final String NOTIFICATION_DATA = "NOTIFICATION_DATA";
private void createNotification(long when, String data){
String notificationContent ="Notification Content Click Here to go more details";
String notificationTitle ="This is Notification";
//large icon for notification,normally use App icon
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
int smalIcon =R.drawable.ic_launcher;
String notificationData="This is data : "+data;
/*create intent for show notification details when user clicks notification*/
Intent intent =new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra(NOTIFICATION_DATA, notificationData);
/*create unique this intent from other intent using setData */
intent.setData(Uri.parse("content://" + when));
/*create new task for each notification with pending intent so we set Intent.FLAG_ACTIVITY_NEW_TASK */
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
/*get the system service that manage notification NotificationManager*/
NotificationManager notificationManager =(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
/*build the notification*/
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
getApplicationContext())
.setWhen(when)
.setContentText(notificationContent)
.setContentTitle(notificationTitle)
.setSmallIcon(smalIcon)
.setAutoCancel(true)
.setTicker(notificationTitle)
.setLargeIcon(largeIcon)
.setContentIntent(pendingIntent);
/*Create notification with builder*/
Notification notification=notificationBuilder.getNotification();
/*sending notification to system.Here we use unique id (when)for making different each notification
* if we use same id,then first notification replace by the last notification*/
notificationManager.notify((int) when, notification);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment