The uri has a value when debugging, but set.sound does't work and does't run the sound program.
private void notification(){
uri = intent.getData();
int notifictionId = 1;
Notification.Builder Builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.eye_rest)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.eye_rest))
.setContentTitle("Eye rest")
.setContentText("It's time to rest the eyes")
.setAutoCancel(true)
.setVibrate(new long[] { 600, 600 })
.setSound(uri);
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_DEFAULT);
channel.enableLights(true);
channel.setLightColor(Color.BLUE);
channel.setSound(uri,null);
Builder.setVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
Builder.setChannelId(channelId);
}
notificationManager.notify(notifictionId, Builder.build());
And I select the sound from the phone's ringtone list by this code :
intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
uri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION | RingtoneManager.TYPE_RINGTONE );
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION | RingtoneManager.TYPE_RINGTONE);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Choose a song for notification");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
startActivity(intent);
Related
I have been trying showing heads up notification as part of Full Screen Intent. It works well in some devices and if device is not locked, it shows up as heads up notification.
But in samsung devices, i have set system notification setting to brief (that shows notification for brief amount of time and then disappear back to system tray). This setting causing heads up notification to appear for small amount of time.
For the same setting, whatsapp and system caller app able to show heads up notification for incoming call.
i have used the following code
Channel creation
private void createFullIntentChannel(){
NotificationManager manager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + ctx.getPackageName() + "/raw/new_ride.mp3" ) ;
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
String NOTIFICATION_CHANNEL_ID = "com.myapp.app.fullintent";
String channelName = "FullRide";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.enableVibration(true);
chan.setImportance(NotificationManager.IMPORTANCE_HIGH);
chan.setSound(sound, attributes);
chan.setShowBadge(true);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
manager.createNotificationChannel(chan);
}
}
Setting content and action buttons on notification
public void showFullScreenIntent(final int notifId, String pickLoc, String dropLoc, String tripType, String accountID, String accountType,
String qrMode, Integer stopCount, Integer vhclType, String estInfo) {
setMediaPlayerFile();
if (mediaPlayer != null) {
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
PlayFile();
}
});
PlayFile();
}
// set content pending intent
Intent fullScreenIntent = new Intent(ctx, NewRideRequest.class);
fullScreenIntent.putExtra("Action", "UserChoice");
fullScreenIntent.putExtra("ID", notifId);
fullScreenIntent.putExtra("BookingID", String.valueOf(notifId));
PendingIntent contentIntent = PendingIntent.getActivity(ctx, ACTION_USER_REQUEST_ID,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
// set action button accept pending intent
Intent acceptIntent = new Intent(ctx, NewRideRequest.class);
acceptIntent.putExtra("Action", "Accept");
acceptIntent.putExtra("ID", notifId);
acceptIntent.putExtra("BookingID", String.valueOf(notifId));
PendingIntent pendingAcceptIntent = PendingIntent
.getActivity(ctx, ACTION_INTENT_REQUEST_ID, acceptIntent,PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
// set action button reject pending intent
Intent rejectIntent = new Intent(ctx, NotificationAction.class);
rejectIntent.putExtra("Action", "Reject");
rejectIntent.putExtra("ID", notifId);
rejectIntent.putExtra("BookingID", String.valueOf(notifId));
PendingIntent pendingRejectIntent = PendingIntent
.getBroadcast(ctx, ACTION_INTENT_REQUEST_ID, rejectIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + ctx.getPackageName() + "/raw/new_ride.mp3") ;
createFullIntentChannel();
String val = dbHelper.GetVehicleMaster(dbHelper.getReadableDatabase(), vhclType);
// set notification builder
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(ctx, "com.myapp.app.fullintent")
.setSmallIcon(R.drawable.ic_yego_logo)
.setContentTitle("New " + (val.contains(",") ? val.split(",")[0] : "") + " Ride Request")
.setContentText(getContent(stopCount, pickLoc, dropLoc))
//.setSound(sound)
.setOngoing(true)
.setTimeoutAfter(10000)
.setDefaults(Notification.DEFAULT_VIBRATE| Notification.DEFAULT_SOUND)
.addAction(R.drawable.payment_success_1, getActionText(R.string.txt_accept, R.color.colorGreen), pendingAcceptIntent)
.addAction(R.drawable.payment_failed_1, getActionText(R.string.txt_reject, R.color.colorRed), pendingRejectIntent)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setFullScreenIntent(contentIntent, true);
Notification incomingCallNotification = notificationBuilder.build();
incomingCallNotification.sound = sound;
//incomingCallNotification.flags = Notification.FLAG_INSISTENT;
final NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notifId, incomingCallNotification);
Handler handler = new Handler(Looper.getMainLooper());
long delayInMilliseconds = 10000;
handler.postDelayed(new Runnable() {
public void run() {
try {
Log.e("MyApp", "Handler runs");
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
notificationManager.cancel(notifId);
}catch (Exception e){
}
}
}, delayInMilliseconds);
}
Please suggest how can i set ongoing heads up notification to be on screen regardless of system setting of notification.
I have implement Push notification firebase services class and add on my project and send notification API Request through so notification proper receive but notification sound work to app active condition only but it will be require all notification receive time.
any one this type condition face and resolve please suggest changes.
String title = Objects.requireNonNull(remoteMessage.getNotification()).getTitle();
String text = remoteMessage.getNotification().getBody();
remoteMessage.getMessageType();
// String channelId = remoteMessage.getNotification().getChannelId();
// Log.d("channelId", "onMessageReceived: "+channelId);
final String CHANNEL_ID = "HEADS_UP_NOTIFICATION";
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Heads Up notification",
NotificationManager.IMPORTANCE_HIGH
);
getSystemService(NotificationManager.class).createNotificationChannel(channel);
Notification.Builder notification = new Notification.Builder(this,CHANNEL_ID)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.demo)
.setAutoCancel(true)
.setVibrate(new long[] { 0,100,300,500,800,1000, 1000, 1000, 1000, 1000 })
.setOngoing(true)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_SOUND)
.setVisibility(Notification.VISIBILITY_PUBLIC);
// custom notification
/* MediaPlayer mp;
mp = MediaPlayer.create(PushNotificationServices.this, R.raw.short_notification_sound);
mp.start();*/
#SuppressLint("UnspecifiedImmutableFlag") PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
notification.setContentIntent(contentIntent);
NotificationManagerCompat.from(this).notify(1,notification.build());
super.onMessageReceived(remoteMessage);
Try to use setSound method instead of setDefaults.
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notification: Notification.Builder = Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.demo)
.setAutoCancel(true)
.setVibrate(longArrayOf(0, 100, 300, 500, 800, 1000, 1000, 1000, 1000, 1000))
.setOngoing(true)
.setPriority(Notification.PRIORITY_MAX)
--> .setSound(defaultSoundUri)
.setVisibility(Notification.VISIBILITY_PUBLIC)
First You have uninstall your app then try again.
If this does not work for then try using below code
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = CommonUtill.random();
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody).setBigContentTitle(getString(R.string.app_name)))
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notification);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel mChannel = new NotificationChannel(channelId,
getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription("desc");
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setSound(sound, attributes); // This is IMPORTANT
if (notificationManager != null)
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(943/* ID of notification */, notificationBuilder.build());
This is reference link
Android Push Notification Sound is missing (Not Working ) background and foreground on android
My program did not show the notificaion bar in android compilesdk28. My code is below. How can I solve this and how do I display the notification in All mobiles?
final String url = userDetailsItem.getIp();
System.out.println("url..."+url);
if (Remaindays .equals("53"))
System.out.println("url..."+url);
{
Context context = null;
String CHANNEL_ID = createNotificationChannel(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.drawable.lesr)
.setContentTitle("my app")
.setContentText(""+url)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(Remaindays+"Days "))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
}
public static String createNotificationChannel(Context context) {
// NotificationChannels are required for Notifications on O (API 26) and above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
String CHANNEL_ID = "Channel_id";
// The user-visible name of the channel.
CharSequence channelName = "Application_name";
// The user-visible description of the channel.
String channelDescription = "Application_name Alert";
int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
boolean channelEnableVibrate = true;
// int channelLockscreenVisibility = Notification.;
// Initializes NotificationChannel.
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, channelName, channelImportance);
notificationChannel.setDescription(channelDescription);
notificationChannel.enableVibration(channelEnableVibrate);
// notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);
// Adds NotificationChannel to system. Attempting to create an existing notification
// channel with its original values performs no operation, so it's safe to perform the
// below sequence.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
return CHANNEL_ID;
} else {
// Returns null for pre-O (26) devices.
return null;
}
}
API => 28 requires Notification Channel
https://developer.android.com/reference/android/app/NotificationChannel
if you want video links
https://www.youtube.com/watch?v=tTbd1Mfi-Sk
Template:
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(getApplicationContext(), DummychatActivty.class);
intent.putExtra("user_id", Config.to_user_id);
intent.putExtra("profile_img_Url", Config.profile_img_Url);
intent.putExtra("user_name", Config.to_user_name);
intent.putExtra("user_image_url", Config.to_user_image_url);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String CHAT_NOTIFICATION_CHANNEL_ID = "101";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant") NotificationChannel Chat_notificationChannel = new NotificationChannel(CHAT_NOTIFICATION_CHANNEL_ID, "Chat Notifications", NotificationManager.IMPORTANCE_MAX);
//Configure Notification Channel
// notificationChannel.setDescription("General Notifications");
Chat_notificationChannel.setLightColor(Color.RED);
Chat_notificationChannel.enableLights(true);
Chat_notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
Chat_notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(Chat_notificationChannel);
}
NotificationCompat.Builder chat_notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), CHAT_NOTIFICATION_CHANNEL_ID)
.setVibrate(new long[]{0, 100})
.setPriority(Notification.PRIORITY_MAX)
.setLights(Color.RED, 3000, 3000)
.setAutoCancel(true)
.setContentTitle(Config.fcm_headline)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setColor(getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.push)
.setLargeIcon(bitmap)
.setGroup("CHAT")
.setContentText(Config.content)
.setAutoCancel(true)
.setSound(defaultSound);
chat_push_count = chat_push_count + 1;
notificationManager.notify(chat_push_count, chat_notificationBuilder.build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
chat_notificationBuilder.setChannelId("101");
}
private void sendNotification(Notification nobj) {
Intent intent = new Intent(context, NotificationActivity.class);
intent.putExtra("Notification", "click");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(context, defaultSoundUri);
r.play();
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(Html.fromHtml(nobj.title))
.setContentText(Html.fromHtml(nobj.desc))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setChannelId("my_channel_01")
.setContentIntent(pendingIntent);
generateNotification(notificationBuilder);
}
Please check this you can get help , its working code in my live project
public void generateNotification(NotificationCompat.Builder notificationBuilder) {
NotificationManager notificationManager =
(NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
String CHANNEL_ID = "my_channel_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getString(R.string.app_name);
// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name,
importance);
// Create a notification and set the notification channel.
notificationManager.createNotificationChannel(mChannel);
}
PreferenceHelper preferenceHelper = PreferenceHelper.getInstance(context);
preferenceHelper.setNotificationId(preferenceHelper.getNotificationId() + 1);
notificationManager.notify(preferenceHelper.getNotificationId(),
notificationBuilder.build());
}
This is my code for making notification and notification is showing but not playing sound please help me to identify mistakes in my code and do we need any permission to play sound,vibrate for notification?
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = "my_channel_01";
CharSequence name = "oreiomilla";
String description ="i love me";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel .setSound(alarmSound,attributes);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages. "+ct)
.setSmallIcon(R.drawable.ic_app_icon)
.setChannelId(CHANNEL_ID) .setTicker("Showing button notification") //
.addAction(android.R.drawable.ic_dialog_alert, "Visit", pIntent) // accept notification button
.addAction(android.R.drawable.ic_dialog_email, "ignore", pIntent)
.build();
mNotificationManager.notify(notifyID, notification);
To set a sound to notifications in Oreo, you must set sound on NotificationChannel and not on Notification Builder itself. You can do this as follows
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel("YOUR_CHANNEL_ID",
"YOUR CHANNEL NAME",
NotificationManager.IMPORTANCE_DEFAULT)
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,
context.getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription(msg);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setSound(sound, attributes); // This is IMPORTANT
if (mNotificationManager != null)
mNotificationManager.createNotificationChannel(mChannel);
}
Try this it will work for you.
private void BigTextNotificationForDays(Context context, String Message, String Author) {
Intent resultIntent = new Intent(context, SplashActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) Calendar.getInstance().getTimeInMillis(), resultIntent, PendingIntent.FLAG_ONE_SHOT);
//To set large icon in notification
// Bitmap icon1 = BitmapFactory.decodeResource(getResources(), R.drawable.big_image);
//Assign inbox style notification
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(Message);
bigText.setBigContentTitle(context.getString(R.string.app_name));
bigText.setSummaryText(Author);
//build notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,createNotificationChannel(context))
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(Message)
.setStyle(bigText)
.setLargeIcon(icon)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setVibrate(new long[]{1000, 1000})
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setPriority(Notification.PRIORITY_HIGH)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
//.setOngoing(true);
// Gets an instance of the LocalNotificationManager service
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//to post your notification to the notification bar
mNotificationManager.notify(3730, mBuilder.build()); // (int) System.currentTimeMillis() set instead of id. if at a time more notification require
}
public static String createNotificationChannel(Context context) {
// NotificationChannels are required for Notifications on O (API 26) and above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
String channelId = "Channel_id";
// The user-visible name of the channel.
CharSequence channelName = "Application_name";
// The user-visible description of the channel.
String channelDescription = "Application_name Alert";
int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
boolean channelEnableVibrate = true;
// int channelLockscreenVisibility = Notification.;
// Initializes NotificationChannel.
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
notificationChannel.setDescription(channelDescription);
notificationChannel.enableVibration(channelEnableVibrate);
// notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);
// Adds NotificationChannel to system. Attempting to create an existing notification
// channel with its original values performs no operation, so it's safe to perform the
// below sequence.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
return channelId;
} else {
// Returns null for pre-O (26) devices.
return null;
}
}
I am creating notification for my apps. I don't want to give a sound when the notification type is a progress bar.
// Run method
progressNotification(context);
public void progressNotification(Context context){
// Simulation download progress
int min = 0;
int max = 100;
while (min<=max){
try{
showNotification(context, true, min, max);
Thread.sleep(100);
}catch(InterruptedException ex){
}
min++;
}
// Send notification with sound
showNotification(context, false, 0, 0);
}
public void showNotification(Context context, Boolean progress, int min, int max){
Intent intent = new Intent(context, EntryActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
String notificationChannelId = createNotificationChannel(context, progress ? false : true);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, notificationChannelId);
mBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(context.getString(R.string.message_title))
.setContentText(context.getString(R.string.message_content))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(context.getString(R.string.mask_message_content)))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
if(progress) {
if(min<max) {
mBuilder.setContentText("Downloading...").setProgress(max, min, false);
}else{
mBuilder.setContentText("Download Complete!").setProgress(0, 0,false);
}
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(234, mBuilder.build());
}
private String createNotificationChannel(Context context, Boolean audio) {
String channelId = "channelId";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "channel_name";
String description = "channel_description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
// Here the condition
if(!audio) channel.setSound(null, null);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
return channelId;
}
return null;
}
If I set showNotification() with progress 'true' it means I disable sound, It works but when I show notificaiton again with progress 'false' it means I enable sound, but it is still disabled.
You can also do it this way and I believe this will create a new notification based on the condition you are implementing:
if (disableSound) {
mBuilder = new NotificationCompat.Builder(context, "")
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setSound(uri)
.setContentTitle("Expiry Date Reminder")
.setContentText("Your text")
.setAutoCancel(true) // clear notification after click
.setContentIntent(pIntent)
.setCategory(Notification.CATEGORY_MESSAGE)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
} else {
mBuilder = new NotificationCompat.Builder(context, "")
.setTicker(model.getProductName())
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setSound(uri)
.setContentTitle("Expiry Date Reminder")
.setContentText("Your text")
.setAutoCancel(true) // clear notification after click
.setContentIntent(pIntent)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}
Then the rest of your code will follow here:
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Your second notification sound is not working because you have created a notification channel with no sound. (To update the Notification Channel You need to Delete the Channel and then add again.)
// Here the condition
if(!audio) channel.setSound(null, null);
I will suggest to remove above line of code and make the following change in NotificationCompat class:
if(progress) {
if(min<max) {
mBuilder
//Set priority to PRIORITY_LOW to mute notification sound
.setPriority(NotificationCompat.PRIORITY_LOW)
.setContentText("Downloading...").setProgress(max, min, false);
}else{
mBuilder
.setContentText("Download Complete!").setProgress(0, 0,false);
}
}
Problem solved, I have to update or create an unique channelId each request NotificationChannel.
private String createNotificationChannel(Context context, Boolean audio) {
String channelId = "channelId" + Boolean.toString(audio); // Here should be an unique id
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "channel_name";
String description = "channel_description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
// Here the condition
if(!audio) channel.setSound(null, null);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
return channelId;
}
return null;
}