Skip to content

Instantly share code, notes, and snippets.

@msomu
Created November 9, 2016 06:23
Show Gist options
  • Select an option

  • Save msomu/876a600cfce8b0c218aaff7998ac0443 to your computer and use it in GitHub Desktop.

Select an option

Save msomu/876a600cfce8b0c218aaff7998ac0443 to your computer and use it in GitHub Desktop.
This is a simple method which will create a Notification on Android.
private void createSimpleNotification() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(101, mBuilder.build());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment