Skip to content

Instantly share code, notes, and snippets.

@andrew-codechimp
Last active April 3, 2018 11:59
Show Gist options
  • Save andrew-codechimp/b930014201a861e794cc to your computer and use it in GitHub Desktop.
Save andrew-codechimp/b930014201a861e794cc to your computer and use it in GitHub Desktop.
[Ongoing Notification without status bar icon] #Android
package your.package.name;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
public class OngoingNotification {
// TODO - specify your own Notification ID
private static final int NOTIFICATION_ID = -555321;
public static void create(Context context) {
// Build the notification, important points are that you only have a small icon, set ongoing and set priority to min
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(context.getString(R.string.notification_title))
.setContentText(context.getString(R.string.notification_text))
.setOngoing(true).setWhen(0)
.setPriority(NotificationCompat.PRIORITY_MIN);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, YourActivity.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 taskStackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
taskStackBuilder.addParentStack(YourActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
taskStackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// NOTIFICATION_ID allows you to update the notification later on.
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
public static void remove(Context context) {
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment