Create notification:
private void sendNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_stat_name);
builder.setContentTitle("My title");
builder.setContentText("Content Text");
Intent removeNotifivationIntent = new Intent();
removeNotifivationIntent.setAction(REMOVE_NOTIFICATION);
PendingIntent removeNotifivationPendingIntent = PendingIntent.getBroadcast(this, 0, removeNotifivationIntent, 0);
builder.setContentIntent(removeNotifivationPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
Create a BroadcastReceiver, it can be in OnCreate:
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (REMOVE_NOTIFICATION.equals(action)) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
nMgr.cancel(NOTIFICATION_ID);
}
}
};
registerReceiver(receiver, filter);