0

I am creating a notification using service class. It works fine with below android O, but for higher versions, the notification is shown for the first time and if I try to show it for the second time it's not showing. Below is my code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Log.e("inside here", "inside ");
        NotificationManager manager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(PRIMARY_CHANNEL, PRIMARY_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        manager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(service, PRIMARY_CHANNEL)
            .setAutoCancel(false)
            .setContentTitle(strLiveBroadcast)
            .setContentText(strAppName)
            .setLargeIcon(largeIcon)
            .setContentIntent(pendingIntent)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setSmallIcon(android.R.drawable.stat_sys_headset)
            .addAction(icon, "pause", action)
            .addAction(R.drawable.ic_stop_white, "stop", stopAction)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setWhen(System.currentTimeMillis())
            .setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
                    .setMediaSession(service.getMediaSession().getSessionToken())
                    .setShowActionsInCompactView(0, 1)
                    .setShowCancelButton(true)
                    .setCancelButtonIntent(stopAction));

    service.startForeground(NOTIFICATION_ID, builder.build());

This is working completely fine in lower versions.

bhaskar
  • 991
  • 1
  • 15
  • 37

1 Answers1

-1

startForeground() doesn't not work with notifications If the NOTIFICATION_ID parameter is set to 0 OR else you need to add Random Id logic every time you call it.

startForeground(0, notification); // Doesn't work...

startForeground(1, notification); // Works!!!

I hope this will work!!

Kalpesh Rupani
  • 991
  • 4
  • 12