Custom Sounds for Android Push Notification

June 26, 2016

Reading time ~2 minutes

Playing a custom sound for android push notifications is really simple with just one trick you have to know. If you are an impatient person who reads the last part of novels first, then move to the end of this post and get the trick :)

Notification Configuration

private Notification prepareNotification () {
    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 1, resultIntent, 0);
    Uri notificationSoundUri = prepareNotificationSoundUri(R.raw.yourSound);
    Notification.Builder builder =
                new Notification.Builder(context)
                        .setSmallIcon(R.drawable.icon)
                        .setContentTitle("Title")
                        .setContentText("Text")
                        .setContentIntent(resultPendingIntent)
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setTicker("Ticker Text")
                        .setSound(notificationSoundUri);
    return builder.build();
}

private static Uri prepareNotificationSoundUri(int soundResourceId) {
    return Uri.parse("android.resource://" + context.getPackageName() + "/" + soundResourceId);
}

IF you support android sdk version lower than 16, then you should use NotificationCompat as follows :

private Notification prepareNotification () {
    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 1, resultIntent, 0);
    Uri notificationSoundUri = prepareNotificationSoundUri(R.raw.yourSound);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.icon)
                    .setContentTitle("Title")
                    .setContentText("Text")
                    .setContentIntent(resultPendingIntent)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setTicker("Ticker Text")
                    .setSound(notificationSoundUri);
    return builder.build();
}

private static Uri prepareNotificationSoundUri(int soundResourceId) {
    return Uri.parse("android.resource://" + context.getPackageName() + "/" + soundResourceId);
}

That’s all. You sent your push notification to your device but couldn’t hear the sound you expect. Now, the mighty trick you should apply is ignoring default sound on notification builder object as follows :

builder.setDefaults(~Notification.DEFAULT_SOUND);

Now you are ready to play your custom sound ;)

Depending on an aar library includes transitive dependencies in a maven project

Depending on an aar library includes transitive dependencies in a maven project Continue reading