Android: Notification do not generate the default sound - java

I am trying to generate FCM notifications with sound. I get the notification etc without issues, but there is no sound at all. I am OK with the default sound of notifications. Please check the below code. It is for API 26 and above.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "xxx";
// The user-visible name of the channel.
CharSequence name = "xxx";
// The user-visible description of the channel.
String description = "xxx";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String CHANNEL_ID = "xxx";
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(this,"xxx")
.setSmallIcon(R.drawable.volusha_notifications)
.setContentText(text)
.setChannelId(CHANNEL_ID)
.setContentIntent(pendingIntent)
.setContentTitle(title)
.setAutoCancel(true)
.build();
// Issue the notification.
mNotificationManager.notify(new Random().nextInt(), notification);
Why is this happening and how to get the default sound?

Change this part :
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(this,"xxx")
.setSmallIcon(R.drawable.volusha_notifications)
.setContentText(text)
.setChannelId(CHANNEL_ID)
.setContentIntent(pendingIntent)
.setContentTitle(title)
.setAutoCancel(true)
.build();
to
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(this,"xxx")
.setSmallIcon(R.drawable.volusha_notifications)
.setContentText(text)
.setChannelId(CHANNEL_ID)
.setContentIntent(pendingIntent)
.setContentTitle(title)
.setSound(RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true)
.build();

Try using RingtoneManager to get Default Notification Uri as:
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(uri);

Related

Retrieving notification intent to redirect user to specific activity of the application

I am making an application that gathers push notifications with NotificationListenerService in Android.
Retrieving notification contents such as the name of the app, contents of the app, package name, notification registered time etc. works very well.
However, when trying to retrieve notifications Intent that redirects the user to a specific Activity of an app when clicked, doesnt work. It won't get Intent. What might be the problem?
try {
//ne.cls_intent = getIntent(sbn.getNotification().contentIntent).toString();
ne.cls_intent =getIntent(notification.contentIntent).resolveActivity(pm).getClassName();
} catch (IllegalStateException e) {
ne.cls_intent = "No Intent";
}
Try this, #Hyeon
Intent intent = new Intent(getApplicationContext(), Your_Desired_Activity.class);
intent.putExtra("Key", value); //for sending data to your specific activity if needed.
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), (int) (Math.random() * 100), intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "101";
//TODO - make the title BOLD - change the notification icons
mBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID);
mBuilder.setContentTitle(message_push)
.setSmallIcon(R.drawable.app_logo)
.setContentText(event_title_push)
.setAutoCancel(true)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setColor(getColor(R.color.text_color))
.setContentIntent(pendingIntent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance);
channel.setDescription(event_title_push);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
mNotificationManager = getSystemService(NotificationManager.class);
channel.setImportance(importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(channel);
}
assert mNotificationManager != null;
// Cancel the notification after the particular notification gets selected
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify((int) (Math.random() * 100) /* Request Code */, mBuilder.build());
This is the total working of showing the notification with title and vibrate and also redirecting to a specific activity.

Unable to create notifications in android

I have typed the following function to get notifications in android.
But I get an error which says Failed to post notification on channel "null". I know that I'm missing some piece of code which seems to be inserted for devices running on some newer versions.
Can I get the exact code to be inserted?
void create_notification(String string){
Intent intent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent)
.setContentText(string)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
}
In your builder, you can add the channelID, for example:
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setChannelId("base_channel") //<-- set the name you feel is proper to your project
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent)
.setContentText(string)
.build();
The documentation (first result on google for the search terms "android notification channel") gives the following example:
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// 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(channel);
}
}
And then on your notification you need to specify the channel ID:
Notification notification = new Notification.Builder(this, CHANNEL_ID)
...
Have you tried this?

Notification not Showing from Service

I searched many other questions related to this topic but found not satisfactory answer also none of them are working for me.
I want to show a continuous notification which should only be terminated by app. But the code i wrote was working a few days ago but not now.
private void GenNotification(String title, String body)
{
try
{
Log.i(Config.TAGWorker, "Generating Notification . . .");
Intent myIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setChannelId("myID")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(false)
.setSmallIcon(R.drawable.floppy)
.setOngoing(true)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notification);
}
catch (Exception e)
{
Log.e(Config.TAGWorker, e.getMessage());
}
}
There is no exception recorded in Logcat, regarding ths. The code is called in onCreate of service. The service is starting correctly i can see in Log cat also there is no exception but notification is not shown. My OS is Android ONE for nokia (PI)
You are using a deprecated NotificationCompat.Builder constructor which takes a single argument (context); and that won't work on starting from Android 8.0 (API level 26).
So, to solve this:
Step 1: Create a Notification channel with the NotificationManager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Notification channels are only available in OREO and higher.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel
("PRIMARY_CHANNEL_ID",
"Service",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Description");
mNotificationManager.createNotificationChannel(notificationChannel);
}
Note: changeargument values as you wish
Step 2:: Use the non-deprecated Notification.Builder class with its two-argument constructor that takes a second argument as the channel ID which you assigned in the first step, where I set it to "PRIMARY_CHANNEL_ID"
Notification notification = new NotificationCompat.Builder
(this, "PRIMARY_CHANNEL_ID")
.setContentTitle("title")
.setContentText("body")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setAutoCancel(true)
.build();
mNotificationManager.notify(0, notification);
Did you check your strings (title and body) is not null if it's null notification wont show
Also check that you call your notification channels when you start your service every time if your android above 7.0
Clear notification when you recall it same id in your case is 1.

startForeground not showing notification again

In my foreground service the code for starting service is as follows:
notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setContentIntent(contentIntent)
.setSmallIcon(R.mipmap.ic_launcher) // the status icon
.setWhen(System.currentTimeMillis()) // the time stamp
.setCustomContentView(getSmallContentView())
.setCustomBigContentView(getBigContentView())
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setOngoing(true);
if (Build.VERSION_CODES.O <= Build.VERSION.SDK_INT) {
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
Notification notification = notificationBuilder.build();
// Send the notification.
startForeground(notificationId, notification);
Calling stopForeground(true) and after that calling startForeground(id,notification) does not show notification again in foreground service.
Any help will be appreciated.

New Firebase notification replacing existing unread Firebase Notification

I followed this link Firebase Notification and can able to send the notification to single device and multiple devices. But, newly arriving notification is replacing already existing unread notification in the tray. Please tell me a way to stop this and display all unread notifications in tray.
Note: Tutorial is regarding GCM. I did necessary changes for FCM.
Solved the issue by generating a random number as id and feeding it in notify() method
public void showSmallNotification(String title, String message, Intent intent) {
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mCtx,
ID_SMALL_NOTIFICATION,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx);
Notification notification;
notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent)
.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.mipmap.ic_launcher))
.setContentText(message)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(m, notification);
}

Categories