I'm trying to create an app with 3 different notification sounds (But not different notification channels), I create custom notification sound, but when I try to change the sound, it stays still the same, I also tried to delete the channel and create it again but notification sound does not change.
First I create Channel:
String CHANNEL_ID = Constants.notification_channel_ID;
int NOTIFICATION_ID = 1991;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = getSystemService(NotificationManager.class);
NotificationChannel existingChannel = mNotificationManager.getNotificationChannel(CHANNEL_ID);
if (existingChannel != null){
mNotificationManager.deleteNotificationChannel(CHANNEL_ID);
}
CharSequence name = getResources().getString(R.string.drink_reminder);
String description = getResources().getString(R.string.notification_to_remind_you_to_drink);
int importance = NotificationManager.IMPORTANCE_HIGH;
if (s1 = true){
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.test_sound);
}else{
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.test_sound1);
}
AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION ).setUsage(AudioAttributes.USAGE_NOTIFICATION).build() ;
NotificationChannel notificationChannel = new NotificationChannel( CHANNEL_ID , name , importance) ;
notificationChannel.setDescription(description);
notificationChannel.enableLights(true) ;
notificationChannel.setLightColor(Color.BLUE) ;
notificationChannel.enableVibration( tinyDB.getBoolean(Constants.settings_notification_vibration_key,true));
notificationChannel.setVibrationPattern( new long []{ 100 , 200 , 300 , 400 , 500 , 400 , 300 , 200 , 400 }) ;
notificationChannel.setSound(sound , audioAttributes) ;
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
Then I create Notifiaction:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(this.getResources().getString(R.string.app_name))
.setContentText(this.getResources().getString(R.string.text))
.setContentIntent(pendingIntent)
.setSound(sound)
.setChannelId(CHANNEL_ID)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, builder.build());
So on first time this code works, when later on I call this method again to and change the sound, notifications are still working with same sound like in beginning, also I can't disable, enable vibration (It stays the same like first time is configured). As you see I'm also trying to recreate notification channel, but still the same.
Any help will be appriciated.
Resolved by setting up a silent notification and adding manual sound and vibration.
So on When I create Channel I use:
notificationChannel.enableVibration(false);
notificationChannel.setSound(null,null);
Also when I build notification I add this code:
.setSilent(true)
Than to vibrate I use this:
private void vibrate (Context context){
Vibrator v = (Vibrator) context.getSystemService(VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(500);
}
}
and for notification ringtone I use this code:
private void playSound(Context context, String SoundUri){
Uri rawPathUri = Uri.parse(SoundUri);
Ringtone r = RingtoneManager.getRingtone(context, rawPathUri);
r.play();
}
When SoundUri is the String that matches the sound from settings user have choosen.
Related
Local notification is not shown again in REALME when I swipe up to clear notification, but swipe right and left notification show again and normal, any else with my code? I try to make id different but it's not working.
Here is my code :
#RequiresApi(api = Build.VERSION_CODES.M)
protected void onOrderChanged(OrderDataModel dm) {
String status = "Status: " + dm.getOrderStatus();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
NotificationChannel channel = new NotificationChannel("1", name, importance);
channel.setDescription(description);
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
.setSmallIcon(R.drawable.icon_launcher)
.setContentTitle("OrderMessage")
.setContentText("OrderId: " + dm.getOrderId() + "\n" + status + "\n" + dm.getNote())
.setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE) //Important for heads-up notification
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX); //Important for heads-up notification
Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, buildNotification);
if (dm.getOrderStatus().equals("P") || dm.getOrderStatus().equals("M"))
dispatchClientStockRequest(this._user.getUserId());
}
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.
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.
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);
}
I have a phone under Android 8 and I begin Android programmation with Android Studio. Some apps like Snapchat or Facebook makes my phone light a led with their custom colors (yellow & blue) when a notification comes.
I want to do the same with my app, I searched a lot and nothing works, the notification appears but not the white light. I checked my phone settings and my app is allowed to light the led.
public class Notification
{
public Notification(String channelId, String channelName, Context context, String title, String body, Intent intent)
{
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
NotificationChannel mChannel = new
NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder nbuilder = new NotificationCompat.Builder(context, channelId)
.setLights(Color.WHITE, 500, 100) // doesn't work
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }) // doesn't work
.setContentTitle(title)
.setContentText(body);
TaskStackBuilder stackBuilder =
TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
nbuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, nbuilder.build());
}
}
I tried calling the setLights() and setVibrate() after setContentText() and I tried calling these voids just before the notify() but it didn't changed anything.
I instanciate my class in the onCreate() :
new Notification("channel-01", "MathWellan Notification", this, "Twitter", "Follow me on Twitter !", new Intent(Intent.ACTION_VIEW, Uri.parse("twitter://user?screen_name=MathWellan")));
Sorry for my bad english, I'm french and I hope you can help me !
Thanks by advance :)
Use this line of code to change notification LED color: your_notification.ledARGB = Color.YOUR_COLOR;
Usage example:
NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notif.cancel(1); // clear previous notification
final Notification notification = new Notification();
notification.ledARGB = Color.MAGENTA;
notification.ledOnMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.notify(1, notification);
Note : screen should be locked when you test it , because notification LED will be highlighted only when screen is off. Maybe that's your problem.