2

This is myService class that extends BroadcastReceiver. Notification sound is played only once if I don't call showNotif. When I do, the sound is played twice. Can anyone help me and tell what's wrong with this code? Thanks.

public class myService extends BroadcastReceiver
{    
    @Override
    public void onReceive(Context context, Intent intent)
    {
        showNotif(context, id, name);
        try {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(context, notification);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void showNotif(Context context, Integer id, String name) {
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, id.toString());
        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.alert)
                .setTicker("bla")
                .setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
                .setContentTitle(name)
                .setContentText("blabla")
                .setContentInfo("blablabla");
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent mIntent = new Intent(context, newClass.class);   
        mIntent .putExtra("ID", id);
        mIntent .putExtra("NAME", name);
        PendingIntent mPending = PendingIntent.getActivity(context, id, mIntent , PendingIntent.FLAG_UPDATE_CURRENT);  
        notificationBuilder.setContentIntent(mPending);
        notificationManager.notify(id, notificationBuilder.build());
    }

}
Einzig7
  • 543
  • 1
  • 6
  • 22
unipin
  • 259
  • 1
  • 3
  • 13
  • DEFAULT_ALL includes DEFAULT_SOUND so the notification is playing a sound in addition to the ring tone that is being played: [Android disable notification sounds](https://stackoverflow.com/questions/35899789/android-disable-notification-sounds) – Elletlar Jul 13 '18 at 17:02
  • Ohh, I see now... I just deleted ".setDefaults(Notification.DEFAULT_ALL)" and now everything is working perfectly. Thank you! – unipin Jul 13 '18 at 17:54
  • Np. Glad it is working :):):) – Elletlar Jul 13 '18 at 18:00

1 Answers1

1

The sound on the notification can be turned off like this:

.setDefaults(0)

Or do not set DEFAULT_ALL

Other default values that can be used:

  • int DEFAULT_ALL: Use all default values (where applicable).
  • int DEFAULT_LIGHTS: Use the default notification lights.
  • int DEFAULT_SOUND: Use the default notification sound.
  • int DEFAULT_VIBRATE: Use the default notification vibrate.

More info here: Android Disable Notification Sounds

Elletlar
  • 3,136
  • 7
  • 32
  • 38