Oreo+ notifications sound issue - android

I'm trying to set a custom sound for notifications. The problems is that it always plays the 1st sound in res/raw folder no matter how many files are in there or how much I'm trying to change the uri. If I remove all files from raw folder no sound is played at all. On Android 6 it works well.
I would like to be able to set a sound from external/internal storage and also a system sound. Is it possible?
Here's my code:
notificationSoundUri = GeneralSettingsManager.getSoundForNotification(getApplicationContext(), site, pushType);
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, Splash.class);
notificationIntent.setAction(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
int smallIcon = R.drawable.big_green_v;
int backgroundColor = 0x8D1919;
String channelId = "default2";
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(smallIcon)
.setColor(backgroundColor)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setDefaults(Notification.DEFAULT_VIBRATE);
if(TextUtils.isEmpty(notificationSoundUri))
{
Timber.e("NOTIFICATION SOUND * MISSING");
mBuilder.setVibrate(new long[]{0L});
}
else
{
Timber.e("NOTIFICATION SOUND * " + notificationSoundUri);
mBuilder.setSound(Uri.parse(notificationSoundUri));
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if(!TextUtils.isEmpty(notificationSoundUri))
{
// Create an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
//remove old channel
try {
mNotificationManager.deleteNotificationChannel(channelId);
}
catch (Exception e)
{
//do nothing
}
// Create new channel
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setSound(Uri.parse(notificationSoundUri), audioAttributes);
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
EDIT:
The code above is from FirebaseMessagingService. The user will select the desired sound for the notification from external storage or from a list of system sounds and this sound should be played when the notification is displayed.

Yes, You can !. You have to use RingtoneManager(For System Sound),
Uri ringSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.sound = ringSound;
For external/internal
u need to find uri for particular Sound file.
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
this.startActivityForResult(intent, 2);
Handle response
#Override
protected void onActivityResult(final int requestCode, final int resultCode,
final Intent intent)
{
if (resultCode == Activity.RESULT_OK && requestCode == 2)
{
Uri uri = Intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (uri != null)
{
this.chosenRingtone = uri.toString();
}
else
{
this.chosenRingtone = null;
}
}
}

Related

Android Custom Notification sound is Not working?

I am getting the custom sound name from the notification and added conditions based on key but always sound only playing in my notification.
I want to play different sounds based on sound keys and how to handle anyone have ideas to help the same.
if (playOrderAssignmentTone) {
if(key.equalsIgnoreCase("sound")){
alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.sound);
} else {
alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.sound2);
}
} else {
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
} catch (Exception e) {
LoggerUtility.PrintTrace(e);
FirebaseCrashlytics.getInstance().log(e.getMessage());
FirebaseCrashlytics.getInstance().recordException(e);
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Notification Builder
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ONE_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
//Optional fields
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setTicker(notificationTicker)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setWhen(System.currentTimeMillis())
//.setSound(alarmSound)
//.setShowWhen(true)
.setOngoing(isOngoing);
// Setting notification sound based on channel id
if (!CHANNEL_ONE_ID.equalsIgnoreCase("auto")) {
notificationBuilder.setSound(alarmSound);
}
So the issue with your code is you need to make separate notification channels for different sounds to work. Above is the code to attach a sound to the notification channel.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
Uri audio = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + File.pathSeparator + File.separator
+ File.separator + getApplicationContext().getPackageName() + File.separator + R.raw.notification);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION).build();
channel.setSound(audio, attributes);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
}
So when you want to play some specific sound with a notification use that notification CHANNEL_ID with the notification builder.
You have to call setSound() method on NotificationChannel instance.
val audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH).apply {
setSound(soundUri, audioAttributes)
}
select notification tone from your mobile:
Uri ringtone=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);;
Intent intent=new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, ringtone);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, ringtone);
((Activity) getContext()).startActivityForResult(intent , 1);
get ringtone path in onActivity result:
if (resultCode == MainActivity.RESULT_OK && requestCode == 1) {
uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
path = uri.toString();
}
saving this path in sqlite database and retrive from in service
when you trigger your notification play this sound just once:
Uri uri;
uri = Uri.parse(myDb.alarmGetRingtone(requestcode));
r = RingtoneManager.getRingtone(getApplicationContext(), uri);
r.play();
I Hope This Code Will Help You
Thank You

MediaPlayer Doesn't finish and stops during Notification

Im using a Broadcast Receiver to send notification at custom time. I use a MediaPlayer to play a sound everytime it fires. The problem is it sometimes just suddenly stops in the middle of the sound playing. This is my code:
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
#SuppressLint("InvalidWakeLockTag")
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TRAININGCOUNTDOWN");
wl.acquire(10*60*1000L /*10 minutes*/);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon);
Intent inteent = new Intent(context, MainActivity.class);
inteent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, xx, inteent, PendingIntent.FLAG_UPDATE_CURRENT);
xx = xx + 1;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(icon)
.setContentTitle("بانگ")
.setContentText(notTitle)
.setPriority(NotificationCompat.PRIORITY_HIGH)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// notificationId is a unique int for each notification that you must define
// Put here YOUR code.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("com.c4kurd.bang");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"com.c4kurd.bang",
"بانگ",
NotificationManager.IMPORTANCE_HIGH
);
channel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
assert notificationManager != null;
int id = context.getResources().getIdentifier(cc(prefs.getString("voices","")), "raw", context.getPackageName());
// Toast.makeText(context, prefs.getString("voices",""),Toast.LENGTH_SHORT).show();
MediaPlayer mp= MediaPlayer.create(context, id);
notificationManager.notify(xx, builder.setVibrate(new long[]{1000,1000}).build());
mp.start();
wl.release();
}
I don't know the issue. Is it because mp.start() is before the Wake Lock?
Thanks in advance.
DEFAULT: This line returns the default notification sound
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
CUSTOM: This line chooses a custom notification sound:
(put this in RAW (resources) folder)
Uri notificationSound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.my_custom_sound_file);
Choose one of the above and add it to your notification:
setSound(notificationSound)
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(icon)
.setContentTitle("Your Title")
.setContentText("Your Content")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setSound(notificationSound)
.setAutoCancel(true);
Remove all extra lines you used your own MediaPlayer.

How can I clear previous activity which is open from the tap on notification in Android?

There is a Reminder application. Now users created 5 Reminders. R1, R2, R3, R4, R5.
And for all reminders time is same. So all reminders came in same time. Now I tap on notification which is R1. and when I tap, it opens a particular activity and show according to details because I sent Id of that reminder in intent.
Now I click on R2/R3/R4/R5, it is opening details according to R1 only instead of R2/R3/R4/R5.
Note: In onReceive, I create notification from that. Also, for all reminders, I open same activity, but details on that activity should be different according to Reminder ID. Also, when I send ReminderId/mReceivedId in intent, it is correct, not the same.
Code:
editIntent = new Intent(context, ReminderDetailActivity.class);
editIntent.putExtra(REMINDER_ID, mReceivedId);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(context, rowId, editIntent, 0);
Complete code (I call createNotification() from onReceive):
private void createNotification() {
int rowId = getRowId(mReceivedId);
Uri mUri;
if (preferenceManager.getRingtoneUri() != null) {
mUri = Uri.parse(preferenceManager.getRingtoneUri());
} else {
mUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
String mTitle = reminder.getTitle();
String id = "1";
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
if (mNotificationManager == null) {
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
Intent editIntent;
if (SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
assert mNotificationManager != null;
NotificationChannel mChannel = mNotificationManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, mTitle, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(context, id);
editIntent = new Intent(context, ReminderDetailActivity.class);
editIntent.putExtra(REMINDER_ID, mReceivedId);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(context, rowId, editIntent, 0);
builder.setContentTitle(mTitle)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setContentTitle(mTitle)
.setSmallIcon(R.drawable.ic_alarm_black_24dp)
.setSound(mUri)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Have you completed your task?"))
.setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE)
.addAction(R.drawable.ic_icon_alarm, context.getString(R.string.pay_now), pendingIntent);
builder.setColor(ContextCompat.getColor(context, R.color.colorPrimary));
} else {
builder = new NotificationCompat.Builder(context, id);
editIntent = new Intent(context, ReminderDetailActivity.class);
editIntent.putExtra(REMINDER_ID, mReceivedId);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(context, rowId, editIntent, 0);
builder.setContentTitle(mTitle)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setContentTitle(mTitle)
.setSmallIcon(R.drawable.ic_alarm_black_24dp)
.setSound(mUri)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_icon_alarm, context.getString(R.string.pay_now), pendingIntent)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Have you completed your task?"))
.setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE)
.setPriority(Notification.PRIORITY_HIGH);
builder.setColor(ContextCompat.getColor(context, R.color.colorPrimary));
}
Notification notification = builder.build();
mNotificationManager.notify(rowId, notification);
}
Welcome to code party 🎉
As i seen, u want start an activity when another is already opened and it can’t get other extras.
So you must before sending another intent, clear bundle or finish activity.
Edited:
use this in your activity
#Override
protected void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
this.setIntent(intent); //just add this line when overrided
}
do it and update me

Can I set a custom ringtone and vibration pattern for a firebase notification?

Recently I started coding my first android project that includes Firebase Cloud Messaging. I use Android SDK 21 (Android 5).
My intention is to let the user choose, which ringtone shall be played and if the device shall vibrate. To do so I created a helper class SettingsHandler, that accesses the user settings like so:
public synchronized static Uri getRingtoneUri(Context context) {
Sharedpreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
return Uri.parse(prefs.getString("ringtone_key"), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString());
}
public synchronized static boolean shouldVibrateOnPush(Context context) {
SharedPreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
return prefs.getBoolean("vibration_flag", true);
}
So when I receive a Notification from Firebase I want to set the sound and the vibrate pattern that the user can set using the methods above.
To get this, I override the onMessageReceived method in MyFirebaseMessagingService that extends - who expected this - FirebaseMessagingService:
public void onMessageReceived(RemoteMessage msg) {
super.onMessageReceived(msg);
if (msg.getNotification() != null) {
Intent activityIntent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, activityIntent, PendingIntent.FLAG_ONE_SHOT);
Notification note = new NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.mipmap.icon)
.setContentTitle(msg.getNotification().getTitle())
.setContentText(msg.getNotification().getBody())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setSound(SettingsHandler.getRingtoneUri(this))
.setVibrate(SettingsHandler.shouldVibrateOnPush ? new long[] {500, 500, 500, 500, 500} : new long[] {0, 0, 0, 0, 0})
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//create notification channels
}
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(1, note);
}
}
However when I send a notification, the default sound always gets played, so I started asking myself, if i have some errors in my way of thinking. Any way how to do it properly? Thanks in advance.
Try using this :
You can pick ringtone using below code:
selsound_button.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select ringtone for notifications:");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentUri);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,RingtoneManager.TYPE_NOTIFICATION);
startActivityForResult( intent, 999);
}
});
You then need to handle the currentUri in onActivityResult method and store it in sharedPreferences for future usage.
The actual work goes here :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 999){
if (data != null) {
currentUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
}
if (Settings.System.canWrite(this)){
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION, currentUri);
}else {
Intent settings = new Intent("android.settings.action.MANAGE_WRITE_SETTINGS");
startActivityForResult(settings, 124);
}
}
if (requestCode == 124){
if (resultCode == Activity.RESULT_OK){
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION, currentUri);
}
}
}
Now get the uri from stored sharedPreferences and use in notification as :
notification.setSound(currentUri);
notification.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }));
Note : You need to have WRITE_SETTINGS permission for this task.
create the Resource folder (directory res)name it raw and put the file (sound file name.mp3) in it and than using the following code for custom sound
Notification note;
.....
......
note.sound = Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.filename);//file name you want to play
for the Oreo and higher SKD version you need to put in Notification Channel
Uri sounduri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.filename); //file name you want to play
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel Channel = new NotificationChannel("CHANNEL_ID","CHANNEL NAME", NotificationManager.IMPORTANCE_DEFAULT)
AudioAttributes attributes;
....
........
Channel.setSound(sounduri, attributes); //set the sound
if (notificationManager != null){
notificationManager.createNotificationChannel(Channel);}
}
OR
using the MediaPlayer class to play sound for notification
MediaPlayer sound = MediaPlayer.create(contex, R.raw.filename);
sound.start();

How to update a notification without notifying in Android?

So I have an app that receives the temperature via MQTT. To avoid getting spammed by notifcations, I want the app to notify once, that is vibrate, play sound and then the next three times (if the notification isn't dismissed) it will only update the temperature value. So:
Notify
Update temp
Update temp
Update temp
5(or 1 if you will) Notify
This is my code:
private final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
private void handleNotification(String message, String topic) {
if (notifManager == null) {
notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
if (isNotifRunning() && ticker < 3) {
updateNotif(message);
ticker++;
} else {
createNotif(message);
ticker = 0;
}
}
private void createNotif(String message) {
Intent intent;
PendingIntent pendingIntent;
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, name, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200});
notifManager.createNotificationChannel(mChannel);
}
intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentTitle(getString(R.string.notifTmpLowTitle))
.setSmallIcon(R.drawable.ic_ac_unit_black_24px)
.setContentText(getString(R.string.notifTmpLowText) + " " + message + Constants.CELSIUS)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(message)
.setColor(getResources().getColor(R.color.colorCold))
.setVibrate(new long[]{100, 200});
} else {
intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentTitle(getString(R.string.notifTmpLowTitle))
.setSmallIcon(R.drawable.ic_ac_unit_black_24px)
.setContentText(getString(R.string.notifTmpLowText) + " " + message + Constants.CELSIUS)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(message)
.setVibrate(new long[]{100, 200})
.setColor(getResources().getColor(R.color.colorCold))
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notifManager.notify(NOTIFY_ID, notification);
}
//TODO Doesn't update, posts a new notification.
private void updateNotif(String message) {
builder.setContentText(getString(R.string.notifTmpLowText) + " " + message + Constants.CELSIUS);
Notification notification = builder.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;
notifManager.notify(NOTIFY_ID, notification);
}
//---------------------------------------------
With this code, I always get, what it looks like, a brand new notification with sound and vibration. I've looked at previous questions regarding this and they all say that it's important to use the same builder and as you can see, I have done this. Is there some change in newer Android versions that I'm not aware of? I've tested on both 7.1.1 and 8.1.
You'll want to call setOnlyAlertOnce(true) to cause updates to your notification to not send sound/vibration.

Categories

Resources