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.
Related
I am receiving a notification but without notification icon...
I don't understand why the icon is not displaying in the notification
notification:
{
title: `Hey ${userName}`,
body: `You Have One New Notification`,
icon: "default",
color: "#0000FF",
sound: "default",
priority: "high",
}
Firebasemessagingservice
String notificationTitle=remoteMessage.getNotification().getTitle();
String notificationbody=remoteMessage.getNotification().getBody();
String click_action=remoteMessage.getNotification().getClickAction();
// String from_user_id=remoteMessage.getData().get("User_data");
NotificationCompat.Builder mbuilder=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.uemround)
.setContentText(notificationbody)
.setContentTitle(notificationTitle)
.setPriority(NotificationCompat.PRIORITY_HIGH);
Intent resultIntent=new Intent(click_action);
//resultIntent.putExtra("user_id",from_user_id);
PendingIntent pendingIntent= (PendingIntent) PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mbuilder.setContentIntent(pendingIntent);
int mnotificationId=(int)System.currentTimeMillis();
NotificationManager mnotifymgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mnotifymgr.notify(mnotificationId,mbuilder.build());
You need to add notification channel for the version oreo and above. Copy the below code and run it. It will work
// NotificationChannels are required for Notifications on O (API 26) and above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "Channel_id";
CharSequence channelName = "Your app name";
int channelImportance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
notificationChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) // channel id is mandatory
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE, 1, 1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
// and icon should be transparent for lollipop and above version
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.drawable.icon_transperent);
} else {
notificationBuilder.setSmallIcon(R.drawable.icon);
}
notificationManager.notify(new Random().nextInt(9999 - 1000) + 1000/* ID of notification */, notificationBuilder.build());
}
} else {
if (notificationManager != null) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "")//no need to add the channel id
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE, 1, 1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
// and icon should be transparent for lollipop and above version
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.drawable.icon_transperent);
} else {
notificationBuilder.setSmallIcon(R.drawable.icon);
}
notificationManager.notify(new Random().nextInt(9999 - 1000) + 1000/* ID of notification */, notificationBuilder.build());
}
}
onMessageRecieved ->
check -> if (remoteMessage.getData().size() > 0) then
you can set your data as per your requirement and then
notificationBuilder = new NotificationCompat.Builder(this, notification_channel_id)
.setContentTitle(remoteMessage.getData().get("Title"))
.setContentText(remoteMessage.getData().get("Body"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
// .setContentInfo("Important")
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(getResources().getColor(R.color.colorAccent))
.setLights(Color.RED, 1000, 300)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setNumber(++numMessages)
.setSmallIcon(R.mipmap.ic_launcher);
sorry for bad english ;-)
I don't know why when I send a notification to marshmallow, there is no sound, but when I send it to oreo, there is a sound notification.
My firebase code is below
Intent intent = new Intent(this, MainActivity.class);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) {
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("idata", idata);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} else {
Context c = getApplicationContext();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
final String CHANNEL_ID = "default";
// The user-visible name of the channel.
final String CHANNEL_NAME = "Default";
NotificationChannel defaultChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(defaultChannel);
intent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("idata", idata);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setWhen(System.currentTimeMillis())
.setSound(defaultSoundUri)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent);
notificationManager.notify("myapp", 0, notificationBuilder.build());
}
I searched all over the internet, but there were no results for this, I really needed this, please help me, any help would really be appreciated. thanks
I had the same problem, but the channel id is only used by oreo & higer android versions. If no sound playing in less than oreo, then make sure you have added "sound": "default"//or any custom filename you have in ur res/ folder.
I accidently missed it in my firebase payload.
Addding sound:"default" solved my issue.
Example:
const notificationContent = {
notification: {
icon: "default",
priority:"high",
sound: "default",
android_channel_id: "myChannelID",
title: "new update",
},
data: {//Used on onMessage() function
priority:"high",
android_channel_id: "myChannelID",
click_action: "FLUTTER_NOTIFICATION_CLICK",
title: "new update",
},
};
Intent intent = new Intent(this, SplashActivity.class);
Bundle bundle = new Bundle();
bundle.putString("splash", psd);
bundle.putString("targetId", targetId);
intent.putExtras(bundle);
intent.setAction(psd);
intent.setAction(targetId);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), id, intent,
0);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.ic_notification_overlay)
.setContentTitle(title)
.setContentText(remoteMessage.getData().get("body"))
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText("" + remoteMessage.getData().get("body")))
.setContentIntent(pendingIntent)
.setSound(defaultSoundUri);
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
String[] events = new String[6];
inboxStyle.setBigContentTitle("" + title);
for (int i = 0; i < events.length; i++) {
inboxStyle.addLine(events[i]);
}
//.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build());
It used to be working, no clue what's happening on new Android devices like Android O. I didn't try back going to old devices, but it's happening on pixel.
Starting in Android 8.0 (API level 26), all notifications must be
assigned to a channel. For each channel, you can set the visual and
auditory behavior that is applied to all notifications in that
channel. Then, users can change these settings and decide which
notification channels from your app should be intrusive or visible at
all
Notification channels
try this code it works perfectly for me.
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(),"channel_01")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(message)
.setContentIntent(resultPendingIntent)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH)
.setChannelId("channel_01")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(inboxStyle)
.setContentTitle(Title);
mNotificationManager.notify(Notification_ID, mBuilder.build());
NotificationChannel channel = new NotificationChannel(Notification_ID, "Playback Notification", NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert mNotificationManager != null;
mBuilder.setChannelId("channel_01");
mNotificationManager.createNotificationChannel(channel);
}else {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(),Notification_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(Title)
.setContentIntent(resultPendingIntent)
.setContentText(message)
.setStyle(inboxStyle)
.setSound(soundUri)
.setAutoCancel(true);
mNotificationManager.notify(Notification_ID, mBuilder.build());
}
I just figured this one out myself, you need to setup Channels in Oreo, see my previous post on the issue - I though it was a master-detail issue!!! Turns out Oreo has an additional attribute you need but it seems to fail silently if you don't provide it.
Set up notification channels. Example code below
public static void createNotificationChannel(final Context context, final
String channelId, final CharSequence channelName, final String channelDescription, final int importance, final boolean showBadge) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
postAsyncSafely("createNotificationChannel", new Runnable() {
#Override
public void run() {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.setDescription(channelDescription);
notificationChannel.setShowBadge(showBadge);
notificationManager.createNotificationChannel(notificationChannel);
Logger.i("Notification channel " + channelName.toString() +
" has been created");
}
});
}
}catch (Throwable t){
Logger.v("Failure creating Notification Channel",t);
}
}
Using the following code from the Android Developer docs I am unable to get sound working in the API 27 (Android O) simulator. It works on an API 24 device. I also double checked in the notification settings that the notification channel is set to play the default sound.
Here is a project with the example code below that you can try on the simulators: Github.
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = "test-channel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel newIncidentChannel = new NotificationChannel(channelId,
"Test Channel",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(newIncidentChannel);
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Test")
.setContentText("Text")
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
int NOTIFICATION_ID = (int) (System.currentTimeMillis()%10000);
notificationManager.notify("test", NOTIFICATION_ID, notificationBuilder.build());
Update 5/16/18:
I'm using the solution here: https://stackoverflow.com/a/46862503/817886 to use the media play to play sounds when the notification comes in. Not ideal but using this until I can find the proper solution.
Update 5/29/18:
The latest version of Android 8.1.0 has fixed this issue.
You should be set sound in NotificationChannel not in NotificaitonBuilder
For Example
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);
String channelId = "test-channel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(channelId ,
"Test Channel",
NotificationManager.IMPORTANCE_DEFAULT)
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,
context.getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription(msg);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setSound(sound, attributes); // This is IMPORTANT
if (mNotificationManager != null)
mNotificationManager.createNotificationChannel(mChannel);
}
Change your
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Test")
.setContentText("Text")
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
Like this :
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Test")
.setContentText("Text")
.setDefaults(Notification.DEFAULT_ALL)
.setSound(RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).
.setAutoCancel(true);
As I've searched how to reveal heads-up, I found a solution that is to set priority high but it still doesn't show heads-ups. I've got a notfication massenger service. Its function is as below. Is there anything I missed in settings?
Heading
mycode:
private void sendNotification(String body, String title) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
remoteViews = new RemoteViews(getPackageName(), R.layout.custom_notification);
remoteViews.setTextViewText(R.id.title, "Firebase");
remoteViews.setTextViewText(R.id.body, body);
remoteViews.setImageViewResource(R.id.icon, R.mipmap.ic_launcher);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
PendingIntent pendingIntent = PendingIntent.getActivities(this, 0, new Intent[]{intent}, PendingIntent.FLAG_ONE_SHOT);
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSmallIcon(R.mipmap.ic_launcher)
.setCustomContentView(remoteViews)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentTitle("Firebase Cloud Messaging")
.setContentText(body)
.setCustomHeadsUpContentView(remoteViews)
.setAutoCancel(false)
.setDefaults(Notification.DEFAULT_ALL)
.setTicker(body)
.setSound(notificationSound)
.setFullScreenIntent(pendingIntent, true)
.setContentIntent(pendingIntent);
notificationManager.notify(0, notifBuilder.build());
}
Try replacing .setContentIntent(pendingIntent) with .setFullScreenIntent(pendingIntent, true) in your Notification Builder.