How Should I Change My Pushnotification Icon For My app - android

I want to change my push notification icon.
Code Snippet :
public class Mymessagingservice extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage){
super.onMessageReceived(remoteMessage);
getimage(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
public void getimage(String title,String message){
NotificationCompat.Builder builder=new NotificationCompat.Builder(this,"mynotification")
.setContentTitle(title)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
R.drawable.otplogo
))
.setSmallIcon(R.drawable.otplogo)
.setAutoCancel(true)
.setContentText(message);
NotificationManagerCompat manager =NotificationManagerCompat.from(this);
manager.notify(999,builder.build());
}
}

Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.
With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/google_blue" />
Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.
You have to put this tag inside Application tag of manifest
Official doc- https://firebase.google.com/docs/cloud-messaging/android/client
Thanks to this guy - https://stackoverflow.com/a/37332514/4741746

Bro its too simple but you have to do it carefully.
First, make a black & white icon for your notification.
Now set it in your notification as a small icon like below.
mBuilder.setSmallIcon(R.mipmap.notification_icon);
now you can set a color but if I am right so you can set only predefined color instead of custom. For custom color you can try with your logic I am giving you a code of a predefined color.
mBuilder.setColor(Color.GREEN);
It will make your notification icon Color green.
Happy Coding!!!
UPDATE
Code for custom notification.
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
0 /* Request code */, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri soundUri = Uri.parse("android.resource://" + mContext.getApplicationContext()
.getPackageName() + "/" + R.raw.sniper_gun);
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.notification_icon);
mBuilder.setSound(soundUri);
if (image!=null) {
mBuilder.setContentTitle(title)
.setContentText(message)
.setAutoCancel(false)
.setLargeIcon(image)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image).setSummaryText(message).bigLargeIcon(null))
.setColor(Color.GREEN)
.setContentIntent(resultPendingIntent);
}
// else {
// mBuilder.setContentTitle(title)
// .setContentText(message)
// .setAutoCancel(false)
// .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
// .setContentIntent(resultPendingIntent);
// }
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
// set custom soundUri
if(soundUri != null){
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
notificationChannel.setSound(soundUri,audioAttributes);
}
assert mNotificationManager != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());

Related

Push Notifications don't vibrate when app is closed

On Android 10, when I receive push notification, the vibration only works if app is opened. If it's in background or closed, vibration doesn't work (but notification get's through and sound works). Is this a bug? Couldn't find it in Google's bug-tracker though.
I send the push notification from our server with data payload, which ensures onMessageReceived() gets called even if app is in background. And it does, I can debug it.
Here's how notification channel is created:
NotificationChannel mChannelUp = new NotificationChannel(CHANNEL_ID_ALERTS_UP, getApplicationContext().getString(R.string.alerts_up), NotificationManager.IMPORTANCE_HIGH);
mChannelUp.enableLights(true);
mChannelUp.enableVibration(true);
// mChannelUp.setVibrationPattern(new long[]{500, 250, 500, 250}); // doesn't help
mChannelUp.setLightColor(Color.BLUE);
AudioAttributes audioAttributesUp = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
mChannelUp.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notif_sound_up), audioAttributesUp);
notificationManager.createNotificationChannel(mChannelUp);
And the notification itself:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID_ALERTS_UP)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_notif)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setLargeIcon(logo)
.setVibrate(new long[]{250, 500, 250, 500})
.setLights(Color.parseColor("#039be5"), 500, 500)
.setContentTitle("some title")
.setContentText("some content")
.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notif_sound_up));
mBuilder.setContentIntent(resultPendingIntent);
Notification notif = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(notificationId, notif);
You need to call the vibration service.
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(2000);
if Your device set Automatically miscellaneous notification channel in notification channel
you can try Firebase default Chanel
public static String NOTIFICATION_CHANNEL_ID ="fcm_fallback_notification_channel";
Channel
NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager;
if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
{
NotificationImportance importance = global::Android.App.NotificationImportance.High;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetSound(sound, alarmAttributes);
notificationChannel.SetShowBadge(true);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
if (notificationManager != null)
{
mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.CreateNotificationChannel(notificationChannel);
}
}
notificationManager.Notify(0, mBuilder.Build());
my class :
class NotificationHelper : INotification
{
private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public static String NOTIFICATION_CHANNEL_ID = "fcm_fallback_notification_channel";
public NotificationHelper()
{
mContext = global::Android.App.Application.Context;
}
public void CreateNotification(String title, String message)
{
try
{
var intent = new Intent(mContext, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
intent.PutExtra(title, message);
var pendingIntent = PendingIntent.GetActivity(mContext, 0, intent, PendingIntentFlags.OneShot);
var sound = global::Android.Net.Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + mContext.PackageName + "/"+Resource.Raw.notification);//add sound
// Creating an Audio Attribute
var alarmAttributes = new AudioAttributes.Builder()
.SetContentType(AudioContentType.Sonification)
.SetUsage(AudioUsageKind.Notification).Build();
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.SetSmallIcon(Resource.Drawable.INH_ICON1);
mBuilder.SetContentTitle(title)
.SetSound(sound)
.SetAutoCancel(true)
.SetContentTitle(title)
.SetContentText(message)
.SetChannelId(NOTIFICATION_CHANNEL_ID)
.SetPriority((int)NotificationPriority.High)
.SetLights(65536, 1000, 500)
//.SetColor(Resource.Color.)
.SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
.SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
.SetVisibility((int)NotificationVisibility.Public)
.SetSmallIcon(Resource.Drawable.INH_ICON1)
.SetContentIntent(pendingIntent);
NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager;
if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
{
NotificationImportance importance = global::Android.App.NotificationImportance.High;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetSound(sound, alarmAttributes);
notificationChannel.SetShowBadge(true);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
if (notificationManager != null)
{
mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.CreateNotificationChannel(notificationChannel);
}
}
notificationManager.Notify(0, mBuilder.Build());
}
catch (Exception ex)
{
//
}
}
}
By the reference of Firebase, when your app is in the background, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.
Messages with both notification and data payload, when received in the background. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity. That time vibration could not happen.
You can try to wake up the application when u received a notification. That might help you.
Firebase Reference
Android Pie And Newer version have some limitations. Check this reference
Suggesting to question here: https://eu.community.samsung.com/t5/galaxy-s10e-s10-s10-s10-5g/s10-has-stopped-vibrating-when-reciving-notifications/m-p/1567092
Try heading to: Settings > Sound and vibration > Vibration intensity > Turn all options to max.
I've now noticed this in the Logcat:
Ignoring incoming vibration as process with uid = 10587 is background,
usage = USAGE_NOTIFICATION_EVENT
To make vibration work even when app in background, you need to use AudioAttributes.USAGE_NOTIFICATION (USAGE_NOTIFICATION_EVENT won't work!) AND also setVibrationPattern on channel:
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
NotificationChannel mChannelUp = new NotificationChannel(CHANNEL_ID_ALERTS_UP, getApplicationContext().getString(R.string.alerts_up), NotificationManager.IMPORTANCE_HIGH);
mChannelUp.enableLights(true);
mChannelUp.enableVibration(true);
mChannelUp.setVibrationPattern(new long[]{0, 300, 250, 300, 250, 300});
mChannelUp.setLightColor(Color.BLUE);
mChannelUp.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notif_sound_up), audioAttributes);
notificationManager.createNotificationChannel(mChannelUp);
Now vibration works when app in background too.
Thanks to ijigarsolanki's answer which helped me realize this.

Android notification badge dot not showing for custom firebase push notification

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.

Not getting Large Icon when app is not in background

I am setting large icon for push notification by using following code.
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.green))
.setSound(defaultSoundUri)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo))
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);
This works fine and shows largeIcon when app is in foreground, but when app is not in foreground, it does not display large icon.
I am testing the app in samsung s7(oreo)
The code snipped you posted works fine only when your app is in the foreground because it only gets called when the app is in the foreground. When the application is in the background, the Android system displays the notification for you (based on the 'notification' object in the JSON object that the server sends to the device). Your receiver is not being called at all. Currently, Firebase Cloud Messaging doesn't support setting a large icon as a payload in the request.
A way around this is to not include a 'notification' object in the POST payload of the message. When you only include 'data' object in the payload, your receiver will be asked to handle the notification even when your application is in the background. Then, you can build the notification the same way as if the app was in the foreground and set a large icon for the notification.
Take a look at this answer for a more detailed explanation about this issue.
Try this,
you're recommended to set default values to customize the appearance of notifications. You can specify a custom default icon and a custom default color that are applied whenever equivalent values are not set in the notification payload.
Add these lines inside the application tag to set the custom default icon and custom color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
Set your application icon transparent
android:icon="#drawable/icon_transper"
and add this lime in AndroidManifest
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/gardi" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
If you set your application icon transparent it can take as notification icon in background.
prefer this link to generate notification icon.
https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=ac_unit&source.space.trim=1&source.space.pad=0&name=ic_stat_ac_unit
I hope this can help you!
Thank You.
It's because you've to set the large icon first and small icon second to that, also you shouldn't use vector images as large icon. Use either Jpeg or PNG images.
new NotificationCompat.Builder(this, channelId)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo))
.setSmallIcon(R.drawable.logo)
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.green))
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);
try once.. Where are you storing your icon in drawable folder .. all the folders like hdpi, xhdpi, xxhdpi.. pls try this once..
You need to check version. If version >= Oreo than you need to add channel id. Please see the sample code below which is working for me:
public void createNotification(Bitmap bitmap, String aMessage, Context context, int icon, String titles, String noti_id, String mid, String att_url, String mname) {
NotificationManager notifManager = null;
final int NOTIFY_ID = 0; // ID of notification
String id = context.getString(R.string.default_notification_channel_id); // default_channel_id
// String title = context.getString(R.string.default_notification_channel_id); // Default Channel
String title = titles;
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
String msg = aMessage;
// bigPictureStyle.setSummaryText("Summary text appears on expanding the notification");
bigPictureStyle.setSummaryText(msg);
bigPictureStyle.bigPicture(bitmap);
if (notifManager == null) {
notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
String m_namse = "Marwadi University - " + mname;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, title, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, FullScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// List<String> test = new ArrayList<String>();
// test.add();
intent.putExtra("title", titles);
intent.putExtra("body", aMessage);
ConstantData.setNotificaitonId(context);
// ConstantData.getNotificaitonId(context);
bundle.putString("values", str);
intent.putExtra("img_path", imageUri);
intent.putExtra("n_id", noti_id);
intent.putExtras(bundle);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.drawable.mu_top_white) // required
.setContentText(m_namse) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(bigPictureStyle)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
} else {
builder = new NotificationCompat.Builder(context, id);
// intent = new Intent(context, AllNotificationActivity.class);
intent = new Intent(context, FullScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("title", titles);
intent.putExtra("body", aMessage);
// intent.putExtra("img_path", imageUri);
intent.putExtra("img_path", imageUri);
intent.putExtra("n_id", noti_id);
intent.putExtra("mid", mid);
ConstantData.setNotificaitonId(context);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.drawable.mu_top_white) // required
.setContentText(m_namse) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(bigPictureStyle)
.setContentIntent(pendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notifManager.notify(NOTIFY_ID, notification);
}
And then Simple call this method:
createNotification(bitmap, message, mContext, R.drawable.main_logo, title, noti_id, mid, att_url, msg);

Notification setSound() doesn't seem to actually set a sound

I recently started coding my first android project including notifications (SDK 21 - Android 5)
Currently, I have a tiny little button, that creates a notification on click and sends it to the app itself. Sound foolish but the purpose is to test if a custom sound and vibrate pattern is used.
This is the notification that gets constructed on click:
Notification note = new Notification.Builder(this.requireContext(), "channel_id")
.setSmallIcon(R.mipmap.icon)
.setContentTitle("Title")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setVibrate(new long[] {500, 500, 500, 500, 500})
.setSound(SettingsHandler.getRingtoneUri(this.requireContext())
.setContentIntent(anyIntent)
.setAutoCancel(true)
.build();
SettingsHandler is a helper class I created to handle settings. Like switching vibration on and off or picking a ringtone. getRingtoneUri() does the following:
public synchronized static Uri getRingtoneUri(Context context) {
SharedPreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
return Uri.parse(prefs.getString("ringtone_uri_key", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString()));
}
When debugging this the result of getRingtoneUri is something like "content://media/internal/audio/media/31". This looks valid to me. However, in a later line, the sound property of the created notification is still null. Amy idea what I'm doing wrong? Thanks in forward.
try this:
Uri alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/raw/ding");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getString(R.string.checkout_channel));
mBuilder.setContentTitle(context.getString(R.string.passenger_name)).setContentText(context.getString(R.string.pit, name)).setSmallIcon(R.drawable.notification_icon).setSound(alarmSound);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
String channelDescription = "Checkout Channel";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
NotificationChannel notificationChannel = new NotificationChannel(context.getString(R.string.checkout_channel),
channelDescription, notifManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setShowBadge(true);
notificationChannel.setSound(alarmSound, audioAttributes);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(iUniqueId, notification);
You need to set the audioAttributes and create your notification channel. This works for me for all Android from 4.2 to 9

Android O reporting notification not posted to channel - but it is

Couple Android O notification questions:
1) I have created a Notification Channel (see below), am calling the builder with .setChannelId() (passing in the name of the channel I created, "wakey"; and yet, when I run the app, I get a message that I've failed to post a notification to channel "null". What might be causing this?
2) I suspect the answer to #1 can be found in the "log" that it says to check, but I've checked logcat & don't see anything about notifications or channels. Where is the log that it says to look in?
Here's the code I'm using to create the channel:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = context.getString(R.string.app_name);
String description = "yadda yadda"
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
Here's the code to generate the notification:
Notification.Builder notificationBuilder;
Intent notificationIntent = new Intent(context, BulbActivity.class);
notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); // Fix for https://code.google.com/p/android/issues/detail?id=53313
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Intent serviceIntent = new Intent(context, RemoteViewToggleService.class);
serviceIntent.putExtra(WakeyService.KEY_REQUEST_SOURCE, WakeyService.REQUEST_SOURCE_NOTIFICATION);
PendingIntent actionPendingIntent = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
_toggleAction = new Notification.Action(R.drawable.ic_power_settings_new_black_24dp, context.getString(R.string.toggle_wakey), actionPendingIntent);
notificationBuilder= new Notification.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setContentIntent(contentIntent)
.addAction(_toggleAction);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);
}
notificationBuilder.setSmallIcon(icon);
notificationBuilder.setContentText(contentText);
_toggleAction.title = actionText;
int priority = getNotificationPriority(context);
notificationBuilder.setPriority(priority);
notificationBuilder.setOngoing(true);
Notification notification = notificationBuilder.build();
notificationManager.notify(NOTIFICATION_ID, notification);
And here's the warning I'm getting:
I think I have learned a couple things that all add up to an answer:
I was using an emulator device, with an image that did not include the Play Store.
The version of Google Play Services on the image was not the latest, so I should have been getting a notification telling me I needed to upgrade. Since that notification didn't get applied to a channel, it didn't appear.
If I set logcat in Android Studio to "No Filters" instead of "Show only selected application", then I found the logs that pointed out that the notification in question was the Play Services "update needed" notification.
So, I changed to a image with the Play Store included, and it showed the notification properly (maybe the channel for that notification was to be set by the Play Store?), let me update to the latest Google Play Services, and I haven't seen that warning since.
So, long story short (too late) - with Android O, if you are using Google Play Services & testing on the emulator, choose an image with the Play Store included, or ignore the toast (good luck on that one!).
I had the same problem, and resolved it by using the constructor
new Notification.Builder(Context context, String channelId), instead of the one which is deprecated onAPI levels >=26 (Android O) :
new NotificationCompat.Builder(Context context)
The following code won't work if your notificationBuilder is built using the deprecated constructor :
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);}
First create the notification channel:
public static final String NOTIFICATION_CHANNEL_ID = "4565";
//Notification Channel
CharSequence channelName = NOTIFICATION_CHANNEL_NAME;
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
then use the channel id in the constructor:
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_timers)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setSound(null)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setContent(contentView)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(picture)
.setTicker(sTimer)
.setContentIntent(pendingIntent)
.setAutoCancel(false);
You gotta create a channel before.
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void notifyThis(String title, String message) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.green_circle)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(0, mBuilder.build());
}
Finally you call this method:
createNotificationChannel();
notifyThis("My notification", "Hello World!");
create a notification using following code :
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannelId(channelId)
.build();
not using :
Notification notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("Some Message")
.setContentText("You've received new messages!")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannel(channelId)
.build();
You have to create a NotificationChannel first
val notificationChannel = NotificationChannel("channelId", "channelName", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(notificationChannel);
This is the only way to show notification for API 26+
I was facing the same problem. It got resolved by creating a NotificationChannel and adding that newly created channel with the notification manager.
I would also like to add that you will receive this error if you're using Build tools v26+:
app/build.grade:
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
targetSdkVersion 26
Downgrading to lowest version should work fine.

Categories

Resources