Search code examples
androidnotificationsbroadcastreceiver

Broadcast Receiver overwrites previous notifications


I've this receiver the notification displays fine only that only last notification is displayed others are overwritten, How to avoid it?

public class MyBroadCastReceiver  extends BroadcastReceiver {

    String TAG="onReceiveBroadcasst";

    public  MyBroadCastReceiver() {

    }

    Context context;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "onReceive: "+constants.notification);
        this.context=context;
        notification_maker("Running Late.","Hurry Up, Time to leave.",BitmapFactory.decodeResource(context.getResources(), R.drawable.late));
        notification_maker("Forecast.","Today's foreacast",BitmapFactory.decodeResource(context.getResources(), R.drawable.late));
        notification_maker("Notification.","Hurry Up, Time to leave.",BitmapFactory.decodeResource(context.getResources(), R.drawable.late));

        city=new PrefManager(context).getStringPref("City",city);
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public  void notification_maker(String Title,String notification,Bitmap bitmap) {
        Bitmap icon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.cloudy);
        NotificationCompat.BigPictureStyle bigPicture = new NotificationCompat.BigPictureStyle();
        bigPicture.bigPicture(icon1);

        ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
        toneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP, 1000);
        Notification notif = new Notification.Builder(context)
                .setContentTitle(Title)
                .setContentText(notification)
                .setSmallIcon(R.drawable.cloudy)
                .setLargeIcon(bitmap)
                .setStyle(new Notification.BigTextStyle().bigText(notification)
                        )
                .build();
        NotificationManager notificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(2,notif);
        Log.i(TAG, Title+"notification_maker: "+notification);
    }
}

Following code will display only last notification, App-logs have log of other notifications being called successfully, how to avoid it?


Solution

  • The old notifications are being overwritten because you are using the same ID for all of them:

    notificationManager.notify(2,notif);
    

    Use different IDs to differentiate the notifications (i.e. don't use 2 to all of your notifications)