pmb
pmb

Reputation: 2327

Do not show notification if it is already shown

In my application I want show a notification in some cases.

When notification is active I do not want to create notification again.

I have activity recognition in my app and when it's detected that I am in car it starts to sound notification every second.

How could I prevent a new build notification if there is at least one active notification there?

Here is my code what I tried:

Intent closeIntent;
        Intent showIntent;
        if (isStart){
            closeIntent = new Intent(this, SwitchButtonListener1.class);
        } else {
            closeIntent = new Intent(this, SwitchButtonListener2.class);
        }

        closeIntent.setAction("No");
        PendingIntent pendingIntentClose = PendingIntent.getBroadcast(this, 0,
                closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action closeAction = new NotificationCompat.Action(R.drawable.btn_close_gray, "No", pendingIntentClose);

        if (isStart){
            showIntent = new Intent(this, SwitchButtonListener1.class);
        } else {
            showIntent = new Intent(this, SwitchButtonListener2.class);
        }

        showIntent.setAction("Yes");
        PendingIntent pendingIntentShow = PendingIntent.getBroadcast(this, 0,
                showIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action showAction = new NotificationCompat.Action(R.drawable.ic_tick, "Yes", pendingIntentShow);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.ic_stat_milebox)
                .setContentTitle(title)
                .setContentText(message)
                .addAction(showAction)
                .addAction(closeAction);
        builder.setSound(alarmSound);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        mNotificationManager.notify(100, builder.build());

Upvotes: 2

Views: 314

Answers (2)

Fahim Foysal
Fahim Foysal

Reputation: 139

Though it is an old question, but I think this answer might help others in the future:

In a case like this, when the user needs to be notified only once and the event is ongoing then using .setOnlyAlertOnce(true) and setOngoing(true) with the builder will solve the problem.

Documentation:

setOnlyAlertOnce(true): Set this flag if you would only like the sound, vibrate and ticker to be played if the notification is not already showing.

setOngoing(true): Set whether this is an ongoing notification. Ongoing notifications cannot be dismissed by the user, so your application or service must take care of canceling them. They are typically used to indicate a background task that the user is actively engaged with (e.g., playing music) or is pending in some way and therefore occupying the device (e.g., a file download, sync operation, active network connection).

Notification notification = new NotificationCompat.Builder(this, notificationChannel.getId())
            .....
            .....
            .setOngoing(true)
            .setOnlyAlertOnce(true)
            .....
            .....
            .build();
Objects.requireNonNull(notificationManager).notify(notificationId, notification);

Upvotes: 2

Andrei T
Andrei T

Reputation: 3083

You can try the following as a sketch:

public class MediaNotificationManager extends BroadcastReceiver {


private final NotificationManager mNotificationManager;

private Context ctx;
private boolean mStarted = false;

public MediaNotificationManager(Context ctx) {
    mCtx = ctx;
    mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    // Cancel all notifications to handle the case where the Service was killed and
    // restarted by the system.
    mNotificationManager.cancelAll();
}

/**
 * Posts the notification and starts tracking the session to keep it
 * updated. The notification will automatically be removed if the session is
 * destroyed before {@link #stopNotification} is called.
 */
public void startNotification() {
    if (!mStarted) {

        // The notification must be updated after setting started to true
        Notification notification = createNotification();
        if (notification != null) {
            mStarted = true;
        }
    }
}

/**
 * Removes the notification and stops tracking the session. If the session
 * was destroyed this has no effect.
 */
public void stopNotification() {
    if (mStarted) {
        mStarted = false;
        try {
            mNotificationManager.cancel(NOTIFICATION_ID);
        } catch (IllegalArgumentException ex) {
            // ignore if the receiver is not registered.
        }
    }
}

@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    LogHelper.d(TAG, "Received intent with action " + action);
    switch (action) {
        //do something with this.            
    }
}

private Notification createNotification() {
  //create and return the notification
}

}

For a bit more read this:
I also used this notification in my code:
https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/mobile/src/main/java/com/example/android/uamp/MediaNotificationManager.java

Upvotes: 0

Related Questions