Android 通知播放音一次

Android Notification play sound once

我正在使用此代码向用户发送通知:

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();
    }

问题是,当我收到多个通知(连续 3+ 个)时,它会播放多次声音,有什么方法可以只播放一次声音吗?

您不需要自己播放声音 - 试试:

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

或者更好,因为您使用的是默认声音: builder.setDefaults(Notification.DEFAULT_SOUND);

顺便说一句 - 避免在代码中使用显式数字(和文字),使用常量: Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN 而不是 Build.VERSION.SDK_INT < 16。它确实提高了代码的可读性。