I'm developing android application which send notification for user and I want to set custom sound for this notification.
It works well for android version less than android 8.
but sound doesn't play for android 8 and higher, so what is the problem ?
this is notification code
Uri sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.sound);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelID, "my app",
NotificationManager.IMPORTANCE_DEFAULT);
AudioAttributes attributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(sound, attributes);
NotificationManager manager = context.getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelID);
builder.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setOngoing(true)
.setSound(sound)
.setAutoCancel(true);
Intent intent = new Intent(context, acticity);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
PendingIntent pi = PendingIntent.getActivity(context, 99,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);
mcompact.notify(99, builder.build());
Why don't you try this code:
// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
// Creating Channel
NotificationChannel notificationChannel = new NotificationChannel(context.getString(R.string.channel_id_prayers),context.getString(R.string.channel_name_prayers),NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(sound,audioAttributes);
Related
I have been trying to create an incoming call type notification for my Android app, written in native Java code, and in many resources online I have read that using the .setOngoing(true) tag on the NotificationBuilder would be enough to have the desired behaviour of the notification being visible, playing the ringtone sound until it is clicked, but that has not worked for me.
I have also tried using the flags Notification.FLAG_INSISTENT and Notification.FLAG_NO_CLEAR without success.
Here is my current code:
private void ringtone(Context context){
String channelId = "call_channel";
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Incoming Call")
.setContentText("You have an incoming call")
.setCategory(Notification.CATEGORY_CALL)
.setOngoing(true)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(contentIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence channelName = "Incoming Calls";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableVibration(true);
long[] pattern = {0, 1000, 500, 1000};
notificationChannel.setVibrationPattern(pattern);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setLegacyStreamType(AudioManager.STREAM_RING)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
notificationChannel.setAllowBubbles(true);
}
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationChannel.setSound(ringtoneUri,att);
notificationManager.createNotificationChannel(notificationChannel);
}else{
notificationBuilder.setSound(ringtoneUri);
}
Notification notification = notificationBuilder.build();
notification.flags |= Notification.FLAG_INSISTENT | Notification.FLAG_NO_CLEAR;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
My intention is to have an incoming call type of notification much like other applications such as MS Teams, Whatsapp, ETC. and my issue is that the notification gets minimized after showing on screen for a few seconds, and the ringtone stops shortly after. Thank you for any help with this.
I am building an android application which push notification in specific times and this working well for me and notification received at these times but I want to turn on screen when Notification received.
I searched for that and I found all answers use PowerManager.FULL_WAKE_LOCK which is deprecated now so I need new way for this, How can I do that ?
this is my Notification code
public void ShowNotification(String title, String message, Class acticity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelID, "my app",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = context.getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelID);
builder.setSmallIcon(R.drawable.notif)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.setAutoCancel(true);
Intent intent = new Intent(context, acticity);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.putExtra("clicked", true);
PendingIntent pi = PendingIntent.getActivity(context, 99,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);
Uri sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.sound);
mp = MediaPlayer.create(context, sound);
mp.start();
mcompact.notify(99, builder.build());
}
I have been trying to get sound and (heads up/pop up) on my notification but nothing is working I read a lot of questions on SO related to this issue and even implement most of them but nothing is working. The only thing which is working with the notification tell yet is its vibration.
Here is my notification channel (in app class)
Im trying to get sound and heads up on channel2
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID_FOR_SERVICE,
utilityClass.NOTIFICATION_CHANNEL_NAME_FIRST, NotificationManager.IMPORTANCE_LOW);
NotificationChannel channel2 = new NotificationChannel(CHANNEL_ID_FOR_REMINDER,
utilityClass.NOTIFICATION_CHANNEL_NAME_SECOND, NotificationManager.IMPORTANCE_HIGH);
channel2.enableVibration(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
channel2.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,audioAttributes);
channel2.setVibrationPattern(new long[]{300, 300, 300});
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
manager.createNotificationChannel(channel2);
}
}
And here I'm creating notification
Intent intent = new Intent(getApplicationContext(), MarkNotificationService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), (int) currentTime, intent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_FOR_REMINDER)
.setSmallIcon(R.drawable.ic_baseline_bookmark_border_24)
.setContentTitle("Title")
.setWhen(System.currentTimeMillis())
.setPriority(NotificationCompat.PRIORITY_MAX)
.addAction(R.drawable.ic_baseline_bookmark_border_24, "Reminder", pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) currentTime, notification);
EDIT: If I manually give floating notification permission in system app sitting then it works fine (heads up)
Add these permissions
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
2.Add build method
public NotificationCompat.Builder createBuilder(Context context
, NotificationManagerCompat manager) {
String channelId = context.getPackageName();
NotificationCompat.Builder notBuilder = new NotificationCompat
.Builder(context, channelId);
notBuilder.setSmallIcon(R.drawable.ic_stat_name);
notBuilder.setColor(Color.parseColor("#3580FF"));
notBuilder.setAutoCancel(true);
notBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND);
notBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notBuilder.setSound(soundUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId
, "Notifications",
NotificationManager.IMPORTANCE_HIGH);
channel.setImportance(NotificationManager.IMPORTANCE_HIGH);
channel.shouldShowLights();
channel.setLightColor(Color.BLUE);
channel.canBypassDnd();
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(soundUri, audioAttributes);
channel.setDescription("Notifications");
notBuilder.setChannelId(channelId);
manager.createNotificationChannel(channel);
}
return notBuilder;
}
3.Show notification
NotificationManagerCompat manager=NotificationManagerCompat.from(context);
NotificationCompat.Builder builder = createBuilder(
context, manager);
builder.setContentTitle(title);
builder.setContentText(message);
builder.setCategory(NotificationCompat.CATEGORY_NAVIGATION);
Intent parentIntent = new Intent(context, ActHome.class);
parentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(context
, NOTIFICATION_ID, parentIntent, PendingIntent.FLAG_ONE_SHOT |
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pIntent);
manager.notify(NOTIFICATION_ID, builder.build());
4.If still doesn't work Uninstall and reinstall the app
The notification did well on virtual device but not on real phone. Did I need to have any user permission? I have no idea to solve this problem :D
here is my code
NotificationManager notificationM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(whitealarm)
.setContentTitle(acti.name)
.setContentText(interval.timeString())
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setOnlyAlertOnce(true)
.setAutoCancel(true);
if(!(audioNotiName.equals("none") ||audioNotiName.equals(""))){
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/raw/"+audioNotiName);
builder.setSound(uri);
}
int notificationid=113;
if(notiHaveVibration){
final Vibrator v = (Vibrator) getSystemService(this.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
v.vibrate(1000);
}
}
notificationM.notify(notificationid,builder.build());
In real phone, you have to check android version.
From Oreo, it changed. So you have to add logic like this.
// create Channel for over oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel("channel", "channel_nm", NotificationManager.IMPORTANCE_HIGH);
mChannel.setVibrationPattern(new long[]{500, 500, 500, 500});
mChannel.setLightColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mChannel.enableVibration(true);
mChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), att);
notificationManager.createNotificationChannel(mChannel);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), mChannel.getId());
} else {
notificationBuilder = new NotificationCompat.Builder(getApplicationContext());
}
notificationBuilder
.setLargeIcon(icon2)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(pushTitle)
.setContentText(contentText)
.setStyle(bigText)
.setLights(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary), 3000, 3000)
.setVibrate(new long[]{500, 500, 500, 500})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent);
int random_num = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(random_num, notificationBuilder.build());
When trying to create a notification within my app, setting a custom notification sound does not work, the system default sound is used. Also, I am trying to enable vibration on my notification, which doesn't work either.
I am trying to set the sound as follows (relevant snippets, see full code below):
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bell);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Order notifications", NotificationManager.IMPORTANCE_MAX);
notificationManager.createNotificationChannel(channel);
channel.setSound(sound,
new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
);
channel.setVibrationPattern(new long[]{0, 500});
} else {
notificationBuilder
.setVibrate(new long[]{0, 500})
.setSound(sound);
}
notificationManager.notify(0, notificationBuilder.build());
My custom sound is a one second long sound snippet, sampled at 44.1 kHz, stored as res/raw/bell.wav. I also tried converting the snippet to different other formats, I tried mp3 and ogg without success.
Regarding the vibration: android.permission.VIBRATE is included in the manifest.
I don't have any more ideas what I am doing wrong. Here is the full code of the sendNotification() function which creates and posts the notification.
private void sendNotification(String messageBody) {
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);
String channelId = getString(R.string.default_notification_channel_id);
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bell);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_web)
.setContentTitle("New order")
.setContentText(messageBody)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
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,
"Order notifications",
NotificationManager.IMPORTANCE_MAX);
notificationManager.createNotificationChannel(channel);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
channel.setSound(sound, att);
channel.setVibrationPattern(new long[]{0, 500});
} else {
notificationBuilder
.setVibrate(new long[]{0, 500})
.setSound(sound);
}
notificationManager.notify(0, notificationBuilder.build());
}
After you create a NotificationChannel you cannot change things like lights, sound and vibrate. Maybe this is the issue. To see changes you need to first remove the app and install it again.