YosiFZ
YosiFZ

Reputation: 7900

Android Notification play sound once

I am using this code for send notification to user:

NotificationManager notificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    Group group = new Group(Integer.parseInt(serverNotification.getGroupID()), serverNotification.getGroupTitle());
    Intent intent = new Intent(this, MainActivity.class);

    if (serverNotification.getType() != Notification.NotificationType.VIDEO_PROCESS_COMPLETED) {
        intent.putExtra(MainActivity.EXTRA_MODE, MainActivity.MODE_GROUP_VIDEOS);
        intent.putExtra(MainActivity.EXTRA_GROUP, group);

        if (serverNotification.getVideoID() != null && serverNotification.getVideoID().length() != 0) {
            intent.putExtra(MainActivity.EXTRA_VIDEO_ID, serverNotification.getVideoID());
        }
    }

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    android.app.Notification.Builder builder = new android.app.Notification.Builder(this)
            .setSmallIcon(R.drawable.notification_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setWhen(System.currentTimeMillis())
            .setContentText(serverNotification.getMessage())
            .setTicker(serverNotification.getMessage())
            .setAutoCancel(true)
            .setContentTitle("MyApp");

    builder.setContentIntent(contentIntent);

    if (Build.VERSION.SDK_INT >= 16) {
        notificationManager.notify(GROUP_NOTIFICATION_ID++, builder.build());
    } else {
        notificationManager.notify(GROUP_NOTIFICATION_ID++, builder.getNotification());
    }

    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }

The problem is that when i get multiple notification(3+ in a row) it play the sound multiple times, there is any way to play the sound only one time ?

Upvotes: 0

Views: 866

Answers (1)

Nuwisam
Nuwisam

Reputation: 830

You do not need to play the sound by yourself - try:

builder.setSound( RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

Or even better, since you are using the default sound: builder.setDefaults(Notification.DEFAULT_SOUND);

And just by the way - avoid using explicit numbers (and literals) in your code, use constants: Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN instead of Build.VERSION.SDK_INT < 16. It really improves code readability.

Upvotes: 1

Related Questions