Android notification channel sound doesn't work - java

I don't know why but no matter what I change the mp3 sound in raw file, the notification just make one sound that its name is the least alphabet, ex: My raw file, the notification will play message_tone no matter what I change the name in the code:
/// Set sound for channel
notificationChannel.setSound(Uri.parse("android.resource://" + getPackageName() + '/' + R.raw.sneeze), null);
My code for set up channel:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
/// Set channel's ID, name, and importance
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_TEST,
"OUTFITTERX",
NotificationManager.IMPORTANCE_HIGH
);
/// Set sound for channel
notificationChannel.setSound(Uri.parse("android.resource://" + getPackageName() + '/' + R.raw.sneeze), null);
// 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(notificationChannel);
}
And show notification:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification notification = new Notification.Builder(this, CHANNEL_TEST)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(message)
.setPriority(Notification.PRIORITY_HIGH)
.build();
/// Show the notification
notificationManager.notify(0, notification);
}
UPDATE
My code for android version lower than android O
/// Create a Notification Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_TEST)
.setSmallIcon(R.drawable.logo) /// Set notification's icon
.setSound(Uri.parse("android.resource://" + getPackageName() + '/' + R.raw.tuturu)) /// Set sound
.setAutoCancel(true) /// Automatically remove notification when user taps it
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}) /// Set sound vibration
.setOnlyAlertOnce(true) /// Only alert Once
.setContentIntent(pendingIntent) /// Set intent it will show when click notification
.setContent(getCustomDesign(title, message)); /// Set the design of notification
notificationManager.notify(0, builder.build());
And I use android Pie 9.0 to test

I'm guessing that this could be because you can not edit a NotificationChannel once created. I think once created it will keep the original configuration (the one used when first creating it). To make it work you will need to delete the app (unistall it) and re install it with the new settings, I mean the new sound file.

Related

Notification comes in notification list but not pop ups on main screen

I am sharing two images please have a look on it you will understand my problem
in fist image notification comes successfully as shown better me notification but
I want it to come and show first on main screen as shown in second image just this telegram notification.
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
// r.play();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
r.setLooping(false);
}
// vibration
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {100, 300, 300, 300};
v.vibrate(pattern, -1);
int resourceImage = getResources().getIdentifier(remoteMessage.getNotification().getIcon(), "drawable", getPackageName());
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSmallIcon(R.mipmap.betterme);
} else {
builder.setSmallIcon(R.mipmap.betterme);
}
Intent resultIntent = new Intent(this, SplashScreen.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentTitle(remoteMessage.getNotification().getTitle());
builder.setContentText(remoteMessage.getNotification().getBody());
builder.setContentIntent(pendingIntent);
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()));
builder.setAutoCancel(true);
builder.setOngoing(true);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
builder.setSound(notification);
mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(notification, audioAttributes);
mNotificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
mNotificationManager.notify(100, builder.build());
}
}
first image
second image
If I understand correctly, you would like to have a heads up notification.
Note, that the android system decides when to make a notification a heads up notification and has the final say - not you the developer. Here you can find some examples when it does so: https://developer.android.com/guide/topics/ui/notifiers/notifications#Heads-up
Make sure that your setup reflects these. From your sample it seems to be the case, but maybe you have changed the notification channel settings (from the app settings), which override your code preferences (the user has precedence over the app).
Additionally, note that if you swipe the heads up notification in a upward direction (not sideways), Android starts a cool off time, where no heads up notifications from that app appears for a few seconds (or more). You can try that with Telegram or any other app as well. After the cool-off time, it starts showing up again like a heads up notification. This is a way Android utilises to prevent apps to be annoying to users.
Seems there is no problem in the notification. But your channel is already created with normal notification and you update to IMPORTANCE_HIGH for NotificationChannel.
Once the channel is created with priority it cannot be changed. So you can either change the channel id or uninstall and reinstall and test it.

Notification not showing - already set chennel as well as small icon, title and text

I have been using notification on my other app and it is working just fine. I have also implemented channelId, but when I am using the similar code for new app, notification is just not showing up. No errors reported.
Following is the code I am using
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notIntent = new Intent(context, hk.class);
// notIntent.setAction(BuildConfig.APP_ID + ".inspire");
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(context, ALARM_REQUEST_CODE,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder mBuilder =
new Notification.Builder(context)
.setContentIntent(pendInt)
.setSmallIcon(R.drawable.spl)
// .setLargeIcon()
.setContentTitle(intent.getStringExtra("not_title"))
.setContentText(intent.getStringExtra("not_text"))
.setPriority(Notification.PRIORITY_HIGH)
.setDefaults(Notification.DEFAULT_VIBRATE)
.addAction(android.R.drawable.ic_menu_share, "Share", PendingIntent.getActivity(context, 0,
new Intent().setAction(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT,
"\n\n" + "-His Holiness Bhakti Rasamrita Swami\n\n").setType("text/plain"), 0))
.setWhen(System.currentTimeMillis())
.setStyle(new Notification.BigTextStyle().bigText(intent.getStringExtra("big_text")));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("daily", "Daily Nectar", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Daily Nectar");
channel.enableLights(true);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId("chId");
}
mNotificationManager.notify(ALARM_REQUEST_CODE, mBuilder.build());
Log.d("AlarmReceiver", "Notification Created"); //this log is printed in console
I have tested using Logs and thus I can ensure that this function is called, so no problem with alarm.
Strangely it doesn't throw any errors also and very similar code on other app is working well. So, I checked the notification setting for this app and found that notification settings are also enabled.
Unable to detect what is the problem. Thank you for the help.
There was a silly mistake.
Note the following code
NotificationChannel channel = new NotificationChannel("daily", "Daily Nectar", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Daily Nectar");
channel.enableLights(true);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId("chId");
channel id passed to new NotificationChannel and channel id set on builder are different. A bug introduced mistakenly during the update.
Happy coding...

How to change the notification settings in android apps?

How can I switch all these settings on programmatically?
I noticed when you install WhatsApp they are all switched on in the beginning(look at the image below).
But I can not find a way to turn them on programmatically.
Here is how I send notifications:
private void sendNotification(Intent intent){
Context context = NotificationService.this;
//open the activity after the notification is clicked
Intent intent1 = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent1, 0);
Notification.Builder builder = new Notification.Builder(context)
.setTicker("Notification")
.setContentTitle("Important Message")
.setContentText("This is an example of a push notification using a Navigation Manager")
.setSmallIcon(R.drawable.ic_add)
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//These are necessary for the notification to pop up
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
builder.setPriority(Notification.PRIORITY_MAX);
builder.setSound(alarmSound);
builder.setLights(Color.BLUE, 500, 500);
}
//after android O we must use notification channels
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Reminder to remind to review your notes",
NotificationManager.IMPORTANCE_HIGH);
if(alarmSound != null){
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
channel.setSound(alarmSound,att);
}
channel.setLightColor(Color.BLUE);
channel.enableVibration(true);
channel.setDescription("Hello Dear friends"); //this is to test what this is
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.setVibrationPattern(new long[]{300, 300, 300});
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
I also added this permission to manifest:
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
Update:
Using this code on the emulator, I get the heads-up notification. But on my Xiaomi device, there is no heads-up notification. It just appears on the status bar. If I manually turn on the floating notification (which you can see in the photo) then I will get heads-up notification. But they are switched off by default. When you install Whatsapp they are all switched on.
Is that a kind of privilege for Whatsapp as it is famout? or is there a way to do it?
By default, when you install a app, the system register's default notification channel (on low priority) that doesn't support head up notification by default, it's turned off. You can't control that.
But what you can do it create your own notification channel with highest priority and then register it on app run once.
After that just pass the channel Id with your notification builder so that system shows the head's up notification which you want.
More information can be found here https://developer.android.com/training/notify-user/channels
I have tried for this but unable to set these settings programmatically. Instead of this I have used following method to open notification settings screen to enable notification sounds/vibration.
private void openNotificationSettingsForApp(String channelId) {
// Links to this app's notification settings.
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && channelId!=null){
intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_CHANNEL_ID,channelId);
intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
}
intent.putExtra("app_package", getPackageName());
intent.putExtra("app_uid", getApplicationInfo().uid);
startActivity(intent);
}

Notification Channel - Is It Possible to Change LightColor After It's Been Set?

I'm trying to change setLightColor with a colour returned from a JavaScript Interface. Unfortunately, NotificationCompat.Builder(context, CHANNEL_ID).setLights has absolutely no sway on API >= 26, so I can't use Intent.putExtra or anything similar.
Is it even possible to change it after it's already been set? I would like it to be dynamic.
EDIT There seems to be some misconception on what I want. I don't want to touch the Broadcast Reciever. It works just fine. I want to change the notification channel. It's not updating setLightColor(Color.___).
In protected void onCreate
String jobColor = someColor; // Will be filled in by other code - different colour every time
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Channel_Name";
String description = "Channel_Description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
channel.enableLights(true);
channel.setLightColor(Color.parseColor(jobColor)); // Dynamically set from above
channel.enableVibration(true);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
My BroadcastReciever - setLight is not applicable for API 26 or higher I believe
public class AlarmReceiver extends BroadcastReceiver {
private final String CHANNEL_ID = "some_channel";
#Override
public void onReceive(Context context, Intent intent) {
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 , new Intent(context, MainPage.class), 0);
String jobColor = intent.getStringExtra("jobColor");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("Upcoming Shift!")
.setContentText("Shift at " + intent.getStringExtra("jobName") + " on " + intent.getStringExtra("jobDate") + " at " + intent.getStringExtra("jobTime"))
.setStyle(new NotificationCompat.BigTextStyle().bigText("You have a shift at " + intent.getStringExtra("jobName") + " on " + intent.getStringExtra("jobDate") + " at " + intent.getStringExtra("jobTime")))
.setLights(Color.parseColor(jobColor), 10000, 1000)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(12345, mBuilder.build());
}
}
You can't change channel color notification, importance etc. programmatically without deleting the channel.
Because a user may have changed the light color manually.
To achieve this programmatically to get the channel and create a new channel with a new id. delete the old channel. Your changes will not reflect if create a channel with the previous id
for reference check WhatsApp application try to change the ringtone from an application and see in a channel at the bottom left x channel is deleted message
Source Android Doc
From createNotificationChannel() description:
This can also be used to restore a deleted channel and to update an existing channel's
* name, description, group, and/or importance.
So you can try this:
NotificationManager notificationManager = getSystemService(NotificationManager.class);
//find created channel
NotificationChannel channel = notificationManager.getNotificationChannel("id");
if (channel != null){
//set new color
channel.setLightColor(0);
//update channel
notificationManager.createNotificationChannel(channel);
}

(Duplicate) Android studio, notification won't appear [duplicate]

I get this message when trying to display a notification on Android O.
Use of stream types is deprecated for operations other than volume
control
The notification is straight from the example docs, and displays fine on Android 25.
Per the comments on this Google+ post:
those [warnings] are currently expected when using NotificationCompat on Android O devices (NotificationCompat always calls setSound() even if you never pass in custom sound).
until the Support Library changes their code to use the AudioAttributes version of setSound, you'll always get that warning.
Therefore there's nothing that you can do about this warning. As per the notification channels guide, Android O deprecates setting a sound on an individual notification at all, instead having you set the sound on a notification channel used by all notifications of a particular type.
Starting with Android O, you are required to configure a NotificationChannel, and reference that channel when you attempt to display a notification.
private static final int NOTIFICATION_ID = 1;
private static final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
...
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setVibrate(new long[]{0, 100, 100, 100, 100, 100})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Content Title")
.setContentText("Content Text");
notificationManager.notify(NOTIFICATION_ID, builder.build());
A couple of important notes:
Settings such as vibration pattern specified in the NotificationChannel override those specified in the actual Notification. I know, its counter-intuitive. You should either move settings that will change into the Notification, or use a different NotificationChannel for each configuration.
You cannot modify most of the NotificationChannel settings after you've passed it to createNotificationChannel(). You can't even call deleteNotificationChannel() and then try to re-add it. Using the ID of a deleted NotificationChannel will resurrect it, and it will be just as immutable as when it was first created. It will continue to use the old settings until the app is uninstalled. So you had better be sure about your channel settings, and reinstall the app if you are playing around with those settings in order for them to take effect.
All that #sky-kelsey has described is good, Just minor additions:
You should not register same channel every time if it has been already registered, so I have Utils class method that creates a channel for me:
public static final String NOTIFICATION_CHANNEL_ID_LOCATION = "notification_channel_location";
public static void registerLocationNotifChnnl(Context context) {
if (Build.VERSION.SDK_INT >= 26) {
NotificationManager mngr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
if (mngr.getNotificationChannel(NOTIFICATION_CHANNEL_ID_LOCATION) != null) {
return;
}
//
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID_LOCATION,
context.getString(R.string.notification_chnnl_location),
NotificationManager.IMPORTANCE_LOW);
// Configure the notification channel.
channel.setDescription(context.getString(R.string.notification_chnnl_location_descr));
channel.enableLights(false);
channel.enableVibration(false);
mngr.createNotificationChannel(channel);
}
}
strings.xml:
<string name="notification_chnnl_location">Location polling</string>
<string name="notification_chnnl_location_descr">You will see notifications on this channel ONLY during location polling</string>
And I call the method every time before I'm going to show a notification of the type:
...
NotificationUtil.registerLocationNotifChnnl(this);
return new NotificationCompat.Builder(this, NotificationUtil.NOTIFICATION_CHANNEL_ID_LOCATION)
.addAction(R.mipmap.ic_launcher, getString(R.string.open_app),
activityPendingIntent)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.remove_location_updates),
servicePendingIntent)
.setContentText(text)
...
Another typical problem - channel default sound - described here: https://stackoverflow.com/a/45920861/2133585
In Android O it's a must to use a NotificationChannel and NotificationCompat.Builder is deprecated (reference).
Below is a sample code :
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
NotificationManager mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, mBuilder.build());

Categories