The following method shows notification with custom sound and on channel. The issue is that the vibration isn't working. I've tried researching and trying but wasn't successful.
private void showNotification(){
Intent intent = new Intent(this, MainActivity.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.messenger);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ChannelId)
.setSmallIcon(R.drawable.ic_stat_facebookmessengernotificationicon)
.setContentTitle("John Doe")
.setContentText("Hey, What's Up!")
.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){
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.build();
NotificationChannel notificationChannel = new NotificationChannel(ChannelId,"Messenger",NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setSound(soundUri,audioAttributes);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{ 100 });
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
mNotificationManager.notify(0, notificationBuilder.build());
}
It's not about custom sound. You are not setting any pattern really. The first value in vibration pattern defines the number of milliseconds to wait before turning the vibrator on. The next value indicates the number of milliseconds for which to keep the vibrator on before turning it off and subsequent values alternate between these two. So in fact pattern sequence means OFF, ON, OFF, ON..., therefore to have any vibration, you need at least two values. I assume you most likely meant this:
notificationChannel.setVibrationPattern(new long[]{ 0, 100 });
Also, calling notificationChannel.enableVibration(true); is redundant as setting valid pattern would automatically enable it (see source).
Related
I can see on MI phone android version 10. i am trying to create a simple notification with title and subtitle. notification also shows up but with no sound and no vibration.
PFB the code:
Intent intent = new Intent(this, MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.drawable.app_icon_white);
notificationBuilder.setColor(getResources().getColor(R.color.theme_color));
} else {
notificationBuilder.setSmallIcon(R.drawable.app_icon_white);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
CharSequence name = getResources().getString(R.string.feroz_channel_name);
String description = getResources().getString(R.string.feroz_channel_description);
channel.enableLights(true);
channel.setLightColor(getResources().getColor(R.color.theme_color));
channel.enableVibration(true);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(77 /* ID of notification */, notificationBuilder.build());
I have vibration permission in Android Manifest. Along with no sound and no vibration. this notification is not visible when device is in locked state. Please suggest what i have missed in the code to achieve this scenario on android 10.
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
In MI Note 5 Pro which has latest MI UI 10.0 with Oreo, so when I try to send push notification by default sound is disable, so i am not able to enable sound programmatically when I am creating a channel for that.
In other Oreo devices notification sound is coming but in MI custom Oreo OS Sound is by default disable
Let me show my code for notification :
var intent = Intent(mContext, HomeActivity::class.java)
intent.putExtra(Constants.EXTRA_FROM_NOTIFICATION, true)
var pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
var uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
var mBuilder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(mFirstContactName + " : " + mListChatWindow[0].message)
.setPriority(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) NotificationManager.IMPORTANCE_HIGH else Notification.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setSound(uri)
.setSmallIcon(R.drawable.ic_app_icon)
.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setVibrate(longArrayOf(0, 100, 1000, 300))
.setAutoCancel(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
var channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH)
channel.description = "NOTIFICATION_DESCRIPTION"
channel.lightColor = Color.LTGRAY
channel.enableVibration(true)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()
channel.setSound(uri, attributes)
var notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
var notificationManager = NotificationManagerCompat.from(mContext)
notificationManager.notify(NOTIFICATION_CHAT_ID, mBuilder.build())
I am also set channel.setSound(uri, attributes) in cannel but sound not coming
Here is the screenshot of Notification channel see there sound icon is disabled, how to enable?
Plz help
I had similar problem in MIUI Global 10.1 with oreo but it was only while using custom sound and not like yours, default sound. Any way let me explain how I solve it and hope it may solve yours.
First thing to consider is where the registration of notification channel is executed. It must be executed in Application.onCreate so that the channel is created even before the notification arrives. I was doing it in onMessageReceived.
Second as I said it was working for default notification sound and not for custom one, I inserted below code while creating notification channel and it worked.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID);
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND); // This line did the magic for me.
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound_notification_plucky);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
CharSequence name = "MyChild";
String description = "All MyChild messages";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationChannel.setDescription(description);
notificationChannel.enableVibration(true);
notificationChannel.setSound(sound, audioAttributes);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
I'm facing same issue and still didn't get satisfying answer, but till that time we can workaround it like so:
final Uri NOTIFICATION_SOUND = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
RingtoneManager.getRingtone(context, NOTIFICATION_SOUND).play();
You need to call this after:
notificationManager.notify(notificationId, notification);
This way you will always get sound playing even if "allow sound" was turned off for your App, and the sound played will be from the system not media (expected behavior from the notifications).
And to avoid having two sounds playing at once (for the devices that don't have this issue), you can turn the sounds off like so:
1- For the Builder:
notificationBuilder.setContentTitle(title)
.set.....
.set.....
.setSound(null);
2- For the channel:
channel.setSound(null, null);
mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH)
This line of code is worked for me it enables all notification settings.
I am trying to add custom sound to notification. Following is my code:
notificationSoundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.error);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "default")
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle("BATTERY FULL") // title for notification
.setContentText("Battery is full. Please plug out the charger. Overcharging may decrease battery life span.")// message for notification
.setSound(notificationSoundUri) // set alarm sound for notification
.setAutoCancel(true); // clear notification after click
mNotificationManager.notify(1, mBuilder.build());
This code is working in pre-lollipop devices and not on Marshmallow. In Marshmallow, it is using phone's default notification sound. I am assuming this problem is for lollipop and higher devices. What am I missing here?
Had this issue for a few tries, it looks like NotificationCompat misses a method for sound on between androids 21 and 25, for notification to work you need to set the sound as this
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, channelId1)
} else {
Notification.Builder(this)
}
...
val audioAttr = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM).build()
builder.setSound(
notification1Sound(), // custom uri
audioAttr)
I don't support versions prior lollipop so this works for me, for older version you might need to add a second version check
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSound(
notification1Sound(),
audioAttr
)
} else {
builder.setSound(notification1Sound(), AudioManager.STREAM_ALARM)
}
You have to use Notification Channel whit Android O (https://developer.android.com/training/notify-user/channels).
This work only on API 26+ because the NotificationChannel class is new and not in the support library.
builder.setStyle(new NotificationCompat.InboxStyle());
The full code:
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MenuScreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
Use these lines of code for custom sound
URI uri=Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.FILE_NAME);//Here is FILE_NAME is the name of file that you want to play
builder.setSound(uri);
Don't forget to add notification channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant")
NotificationChannel channel = new NotificationChannel("XYZ", "ABC",NotificationManager.IMPORTANCE_MAX);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, mBuilder.build());
Below mentioned code is working for all devices below android O verison. For android O,
addAction() method is not working i.e. button click is not working in android O.
Any help would be appreciated.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mediaPlayerReceiver = new Intent("com.consult.news.receiver.ACTION_PLAY");
mediaPlayerReceiver.putExtra("NewsArticle", news);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, mediaPlayerReceiver, PendingIntent.FLAG_UPDATE_CURRENT);
Intent dismissNotification = new Intent("com.consult.news.receiver.DISMISS");
dismissNotification.putExtra("Notification_ID", 1);
PendingIntent dismissNotificationIntent = PendingIntent.getBroadcast(context, 0, dismissNotification, PendingIntent.FLAG_UPDATE_CURRENT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_channel_01";
String CHANNEL_NAME = "my Channel Name";
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "my_channel_01")
.setSmallIcon(R.drawable.ic_notification_white)
.setColor(ContextCompat.getColor(context, R.color.accent))
.setContentTitle(context.getString(R.string.Consult_Univadis_Title))
.setStyle(new NotificationCompat.BigTextStyle().bigText(news))
.addAction(isPlaying ? R.drawable.ic_notification_white : R.drawable.ic_notification_white, isPlaying ? "Play" : "Pause", pendingIntent)
.addAction(R.drawable.ic_notification_white, "Close", dismissNotificationIntent)
.setOngoing(true)
.setAutoCancel(false);
notificationManager.notify(1, builder.build());
I ran into the same, in Android Oreo you need to make it a explicit Intent (is not enough with putting the receiver on the manifest, in fact, it won't pay attention to that), so when you make the intent, make it explicit using the setClass method:
Intent mediaPlayerReceiver = new Intent("com.consult.news.receiver.ACTION_PLAY");
mediaPlayerReceiver.putExtra("NewsArticle", news);
mediaPlayerReceiver.setClass(this, YourReceiver.class);
Where "this" is the Context and YourReceiver, is the Receiver class that you are expecting to listen to the action.
You will have to do the same for the dismissNotification intent
Let me know if this worked for you.