I have Firebase messaging with my andriod application. I am using Firebase to send push notifications. I want to change the default notification sound to a custom one. how can i do it ?
Uri defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.mipmap.ic_notif)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setCustomBigContentView(remoteViews)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))
;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Integer.parseInt(id) /* ID of notification */, notificationBuilder.build());
}
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" +R.raw.pop);
notification.defaults |= Notification.DEFAULT_VIBRATE;
Use above code to add custom sound from resources.
The above code can be used if we are using Notification class.
Notification notification = new Notification(icon, tickerText, when);
As you are using NotificationBuilder, use the below code.
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.mipmap.ic_notif)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(sound)
.setContentIntent(pendingIntent)
.setCustomBigContentView(remoteViews)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))
;
Use setSound() method to set the sound
if(!silent) { // check if phone is not in silent mode
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(9999, notificationBuilder.build());
}
}
Or you can use
{
"to" : "XXYYXXYY...",
"notification" : {
"body" : "The stock opened on a bullish note at Rs. 449 and touched a high of Rs. 461.35, up 5.06 per cent over its previous closing price on the BSE. A similar movement was seen on the NSE where the stock opened at Rs. 450 and hit a high of Rs. 463.70, up 5.32 per cent.",
"title" : "Stocks in focus: Kalpataru Power, Punj Lloyd, J B Chem, Bharti Airtel",
"icon" : "ic_stock",
"sound" : "res_notif_sound"
}
}
If you want to use default sound of the device, you should use:
"sound": "default".
Related
We are trying to implement heads up notification for our app. Before asking question here, we went through all the threads that discussed this issue. Taking references, we went ahead implementing the code, but still heads up notification does generate the push but not in the heads up fashion (like whatsapp), despite creating channel as needed in version above oreo and setting priority and importance to max and high respectively.
The particular code is as given below
private void sendMyNotification(String title, String message, String click_action, String uri, String tag, String nid) {
//On click of notification it redirect to this Activity
Intent intent = new Intent(click_action);
intent.putExtra("uri", uri);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
int notification_id = nid!=null ? Integer.parseInt(nid) : MainActivity.ASWV_FCM_ID;
String channelId = MainActivity.asw_fcm_channel;
Uri soundUri= Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + BuildConfig.APPLICATION_ID + "/" + R.raw.adhan);
NotificationChannel channel = new NotificationChannel(channelId, "name",
NotificationManager.IMPORTANCE_HIGH); // for heads-up notifications
channel.setDescription("description");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, MainActivity.asw_fcm_channel)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
Notification noti = notificationBuilder.build();
noti.flags = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
notificationManager.notify(notification_id, notificationBuilder.build());
}
}
Shall appreciate should you guide us as where we are going wrong.
Be informed we are trying to send push notification to a device with custom sound. The custom mp3 file (120 seconds) is stored in res/raw file. The notification is sent successfully, but the sound never plays out even after many tries. The code is as given below:
Update:Based on suggestion given in the comments, created a notificationchannel and set the sound in it, but still its not working. Worse, unable to build apk at all.
Uri soundUri= Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + BuildConfig.APPLICATION_ID + "/" + R.raw.adhan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, MainActivity.asw_fcm_channel)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
Notification noti = notificationBuilder.build();
noti.flags = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.FLAG_AUTO_CANCEL;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel("345",
"new",
NotificationManager.IMPORTANCE_HIGH);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
// Configure the notification channel.
mChannel.setDescription(message);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setSound(soundUri, attributes); // This is IMPORTANT
if (NotificationManager != null)
NotificationManager.createNotificationChannel(mChannel);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notification_id, notificationBuilder.build());
We are at loss as where we are going wrong. Please guide us as how we solve this issue.
I have implemented custom view for firebase push notification. For custom view we need to remove "notification" key from push Json so that it can be handled even when app is closed like below:
{
"data": {
"detail": {
}
},
"to": ""
}
For creating custom notification I used below code:
private void generateNotification(String title, String message, Intent intent) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
String channelId = getString(R.string.default_notification_channel_id);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notificationCount, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
/*
* Custom notification layout
* */
String notificationHeaderText = getResources().getString(R.string.app_name) + " \u2022 "
+ DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME);
RemoteViews collapsedView = new RemoteViews(getPackageName(), R.layout.view_collapsed_notification);
collapsedView.setTextViewText(R.id.timestamp, notificationHeaderText);
collapsedView.setTextViewText(R.id.content_title, title);
collapsedView.setTextViewText(R.id.content_text, message);
RemoteViews expandedView = new RemoteViews(getPackageName(), R.layout.view_expanded_notification);
expandedView.setTextViewText(R.id.timestamp, notificationHeaderText);
expandedView.setTextViewText(R.id.content_title, title);
expandedView.setTextViewText(R.id.notification_message, message);
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.footer_click);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_inkclick_logo_colored)
.setSound(soundUri)
.setGroup(GROUP_KEY_INKCLICK)
.setAutoCancel(true)
.setGroupSummary(true)
.setCustomContentView(collapsedView)
.setCustomBigContentView(expandedView)
.setContentIntent(pendingIntent);
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (manager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
getResources().getString(R.string.default_notification_channel_id), NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.setLightColor(Color.MAGENTA);
channel.setVibrationPattern(new long[]{0, 1000/*, 500, 1000*/});
channel.enableVibration(true);
channel.setShowBadge(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(soundUri, audioAttributes);
manager.createNotificationChannel(channel);
}
manager.notify(0, notificationBuilder.build());
}
else {
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.notify(0, notificationBuilder.build());
}
}
notificationCount += 1;
}
I have added channel.setShowBadge(true); after reading the official notification badge documentation here as well as other answers on stackoverflow like this and this.
I have also tried uninstalling the app and restarting the device but the badge is not showing.
Device is running on API 28(Pie).
You can set style by adding below line
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
add this code
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_inkclick_logo_colored)
.setSound(soundUri)
.setGroup(GROUP_KEY_INKCLICK)
.setAutoCancel(true)
.setGroupSummary(true)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(collapsedView)
.setCustomBigContentView(expandedView)
.setContentIntent(pendingIntent);
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
You can set the style of the Android notification badge like this:
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
The overall code can look like this:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_inkclick_logo_colored)
.setSound(soundUri)
.setGroup(GROUP_KEY_INKCLICK)
.setAutoCancel(true)
.setGroupSummary(true)
.setCustomContentView(collapsedView)
.setCustomBigContentView(expandedView)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setContentIntent(pendingIntent);
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
You need to specify the title or text (setContentTitle or setContentText). Because Android SDK uses it to describe notification in the window which appears when you long-click to the app icon. I don't know why this is not specified in the documentation, but it works this way.
I am adding custom sound for my application. The custom ringtone is playing when the application is in the foreground but the custom sound is not playing when the application is in background.
private void sendMyNotification(String message) {
Intent intent = new Intent(this, BaseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.ring);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
.setSmallIcon(R.mipmap.iconfinal)
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if(soundUri != null){
// Changing Default mode of notification
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
// Creating Channel
NotificationChannel notificationChannel = new NotificationChannel("CH_ID","Testing_Audio",NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(soundUri,audioAttributes);
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
mNotificationManager.notify(1, notificationBuilder.build());
}
First you need to pass your sound file name from server side.
like below example:
{
"to": "firebase_notification_token",
"notification": {
"title": "Push notification title",
"body": "Push body",
"sound": "filename", <-- point to src/res/raw/filename.mp3
}
}
You need to add below code to play custom sound while app is in background.
val channelId = getString(R.string.app_name)
val NOTIFICATION_SOUND_URI =
Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + BuildConfig.APPLICATION_ID + "/" + R.raw.filename)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
val notification: Notification
notification = notificationBuilder.setSmallIcon(R.drawable.ic_logo_white).setTicker(getString(R.string.app_name)).setWhen(0)
.setAutoCancel(true)
.setContentTitle(getString(R.string.app_name))
.setSound(NOTIFICATION_SOUND_URI)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(messageBody)
.build()
For more detail refer to this Document.
Thanks to Ilya Eremin for great article.
I want to notify the user when message arrived, I used two types of notifications,(New:
supported by >=4.1), and the other type is for older device, I write a condition to check the device SDK version and notify by the suitable notyfication type:
if(Build.VERSION.SDK_INT>=4.1) {
Notification notification = new Notification.Builder(context)
.setContentTitle("new message from" + msg.getString(ConstantsGCM.NAME_CLM))
.setContentText(msg.getString(ConstantsGCM.BODYCLM))
.setSmallIcon(icon)
.setLargeIcon(bm)
.setAutoCancel(true)
.setWhen(when).setVibrate(viber)
.setContentIntent(contentIntent)
.build();
if (EntryActivity.useSound.equals("yes"))
if (!ring.equals(""))
notification.sound = (Uri.parse(ring));
else notification.defaults = Notification.DEFAULT_SOUND;
mNotificationManager.notify(110, notification);
}else { //old type..
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.newlogo)
.setContentTitle("new message from" + msg.getString(ConstantsGCM.NAME_CLM))
.setContentText(msg.getString(ConstantsGCM.BODYCLM))
.setContentIntent(contentIntent)
.setLargeIcon(bm)
.setAutoCancel(true)
.setWhen(when);
if (EntryActivity.useSound.equals("yes"))
if (!ring.equals(""))
mBuilder.setSound(Uri.parse(ring));
else mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mNotificationManager.notify(110, mBuilder.build());
}
but In older devices the notifications don't work at all!
Any help?
point: no errors, no exceptions, just the notification doesn't apeare!
In your else statement try this:
mNotificationManager.notify(110, mBuilder.getNotification());