Notification Not Showing In Android Studio - android

I'm using Kotlin and Android Studio to try and push a Notification in a test app. I followed the instructions in the Android Developers site on How to create a Notification (https://developer.android.com/training/notify-user/build-notification) but I seem to be doing something wrong as my Notification is not showing anywhere. Here's my code:
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager = message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
I really don't know what I'm missing so I would be grateful for any help.

According to your code, you are not creating a Notification channel.
Notification channel is necessary from Android Oreo and above
So if you are running the app Android O and above devices without a notification channel, your notification won't show up.
Create Notification Channel
fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "all_notifications" // You should create a String resource for this instead of storing in a variable
val mChannel = NotificationChannel(
channelId,
"General Notifications",
NotificationManager.IMPORTANCE_DEFAULT
)
mChannel.description = "This is default channel used for all other notifications"
val notificationManager =
mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
}
Then create a notification using the same channelId while creating a notification.
createNotificationChannel()
val channelId = "all_notifications" // Use same Channel ID
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context, channelId) // Create notification with channel Id
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager =
message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
Hope it helps.

try something like
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0)
val mNotificationManager =
message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Don't forget this check
val channel = NotificationChannel (
channelId,
"my_notification",
NotificationManager.IMPORTANCE_HIGH
)
channel.enableLights(true)
channel.lightColor = Color.GREEN
channel.enableVibration(false)
val builder = NotificationCompat.Builder(this.context, "channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
mNotificationManager.createNotificationChannel(channel)//Notice this
mNotificationManager.notify(123, builder.build())
}
else {
//Create Notifcation for below Oreo
}
Does your Logcat say something like:
E/NotificationManager: notifyAsUser: tag=null, id=123, user=UserHandle{0}
Also have a look at your line:
val intent = Intent(context, Profile::class.java)
IF all else fails create a test Actvity with hello world.
And then make the line look like:
val intent = Intent(context, testActivity::class.java)
Remember to add the activity to your Manifest
The following line
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
should not have a semi colon. Kotin doesn't need this.
Is Profile your Class or System Class?

Try out this method and you can pass message and title dynamically :
private fun showNotification(title: String?, body: String?) {
val intent = Intent(this, Profile::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}

Related

Incoming Phone Call notification has no ringtone sound or vibration

Method to create a Notification Channel
private fun createChannel(notificationManager: NotificationManager) {
val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_RING)
.build()
val incomingPhoneCallChannel = NotificationChannel(
mNotificationManager.INCOMING_PHONE_CALL_CHANNEL_ID, "Incoming phone call",
NotificationManager.IMPORTANCE_HIGH
).apply {
setSound(uri, audioAttributes)
vibrationPattern = mNotificationManager._VIBRATION_PATTERN
enableVibration(true)
}
notificationManager.createNotificationChannel(incomingPhoneCallChannel)
}
Method to notify about the call
override fun notify(context: Context) {
val notificationManager = mNotificationManager.notificationManager
val notificationChannel = notificationManager.getNotificationChannel(mNotificationManager.INCOMING_PHONE_CALL_CHANNEL_ID)?: createChannel(notificationManager)
val contentTitle = "Incoming Call"
val contentIntent = Intent(context, PhoneCallReceiver::class.java)
val pendingIntent =
PendingIntent.getBroadcast(context, 0, contentIntent, PendingIntent.FLAG_IMMUTABLE)
val ringtone =RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
var builder = NotificationCompat.Builder(
context,
mNotificationManager.INCOMING_PHONE_CALL_CHANNEL_ID
)
.setContentTitle(contentTitle)
.setContentIntent(pendingIntent)
.setContentText("phone call")
.setColor(ContextCompat.getColor(context, R.color.ic_launcher_background))
.setCategory(NotificationCompat.CATEGORY_CALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_phone_black_24dp)
.setOngoing(true)
.setSound(ringtone)
builder.setVibrate(mNotificationManager._VIBRATION_PATTERN
val notification = builder.build()
notification.flags = Notification.FLAG_INSISTENT
notificationManager.notify("Incoming Call", mId, notification)
}
The above code does give me notification with a default notification that sounds like a single "TING!!". It doesn't change the sound even if I select different Ringtones from the notification channel settings and doesn't vibrate at all.
Make sure the audio permission is allowed:
// Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Change TYPE_RINGTONE to TYPE_NOTIFICATION

Vibrate functionality implementing in FCM

I am implementing FCM in my app. I want my device to vibrate and blink led on receiving notification. But it seems to not work as i expected. Is there any way to achieve this with FCM. Here's my code:
private fun sendNotification(messageBody: String?) {
val intent = Intent(this, HomeActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
val channelId = "my_channel_id"
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(applicationContext, channelId)
.setAutoCancel(true)
.setSmallIcon(R.drawable.splash_icon)
.setContentText(body)
.setContentTitle(title)
.setContentIntent(pendingIntent)
.setSound(defaultSoundUri)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000))
.setLights(0, 2000, 500)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel =
NotificationChannel(channelId, "app", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0, notificationBuilder.build())
}

setFullScreenIntent is not coming to foreground in samsung Android OS 11

I am trying to show Call notification like whatsup with audio
I had implemented full screen notification for call using setFullScreenIntent and pending intents as below but in other devices I am getting notification to foreground except in Samsung device with OS 11.
var notificationBuilder: NotificationCompat.Builder? = null
val ringUri: Uri = Settings.System.DEFAULT_RINGTONE_URI
var contentView = RemoteViews(packageName, R.layout.call_notification_layout)
contentView.setOnClickPendingIntent(R.id.imgCallYes, receiveCallPendingIntent)
contentView.setOnClickPendingIntent(R.id.imgCallNo, cancelCallPendingIntent)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationBuilder = NotificationCompat.Builder(
applicationContext,
CHANNEL_ID
)
.setSmallIcon(R.mipmap.ic_launcher)
.setContent(contentView)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setSound(ringUri)
.setFullScreenIntent(callDialogPendingIntent, true)
val notificationChannel = NotificationChannel(
CHANNEL_ID,
"My Notifications",
NotificationManager.IMPORTANCE_HIGH
)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
// Configure the notification channel.
val att = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
notificationChannel.setSound(ringUri, att)
notificationChannel.description = "body"
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.vibrationPattern = longArrayOf(0, 1000, 500, 1000)
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
} else {
notificationBuilder =
NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContent(contentView)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setSound(ringUri)
.setFullScreenIntent(callDialogPendingIntent, true)
}
var incomingCallNotification: Notification? = null
if (notificationBuilder != null) {
incomingCallNotification = notificationBuilder.build()
}
startForeground(NOTIFICATION_ID, incomingCallNotification)
IN Android 12 I added PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT for pending intent, now notification is coming

Android 10: No custom sound in notification

I'm creating a channel with custom sound. The notifications are correctly displayed but the sound played is still the default one.
Creation of the channel
val audioAttribute = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
val sound = Uri.Builder().scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(packageName)
.path(R.raw.notifsound.toString()).build()
alertChannel.apply {
enableVibration(true)
description = "Signal alert channel"
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
setSound(sound, audioAttribute)
}
notificationManager.createNotificationChannels(listOf(locationNotificationChannel,gpsStatusChannel,alertChannel))
I checked the URI with this
(contentResolver as ContentResolver).openInputStream(sound)
And it can read the file.
I found the problem.
Once you create a notification channel, you can't change the sound of it.
So you have two solutions:
Uninstall the app and install again
Or change the notification channel id to create a new one with the right configuration.
Hope this help.
I solved the issue by uninstalling the app and reinstalling it
private fun sendNotification(remoteMessage: RemoteMessage) {
val fullScreenIntent = Intent(this, IncomingActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
putExtra(Constants.ROOM_ID, remoteMessage.data[Constants.ROOM_ID])
putExtra(Constants.REMOTE_MSG_INVITER_TOKEN, remoteMessage.data[Constants.REMOTE_MSG_INVITER_TOKEN])
}
val fullScreenPendingIntent: PendingIntent? = TaskStackBuilder.create(this).run {
// Add the intent, which inflates the back stack
addNextIntentWithParentStack(fullScreenIntent)
// Get the PendingIntent containing the entire back stack
getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
}
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build()
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(resources.getString(R.string.app_name), "Incoming call...", NotificationManager.IMPORTANCE_HIGH)
notificationChannel.description = "Someone is calling you..."
notificationChannel.setSound(Settings.System.DEFAULT_RINGTONE_URI, audioAttributes)
notificationManager.createNotificationChannel(notificationChannel)
}
val notificationBuilder =
NotificationCompat.Builder(this, resources.getString(R.string.app_name))
.setSmallIcon(R.drawable.icon)
.setContentTitle("Incoming call")
.setContentText("Someone is calling you...")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setAutoCancel(true)
.setSound(Settings.System.DEFAULT_RINGTONE_URI)
.setChannelId(resources.getString(R.string.app_name))
.setContentIntent(fullScreenPendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.icon))
val incomingCallNotification = notificationBuilder.build()
notificationManager.notify(0, incomingCallNotification)
}

Why my notification not work in background when my app is kill and close in android

When my app is open, notification works perfectly but when in background it doesn't work .I want the notification to be displayed even when my app is killed or closed in my phone. But it is not working. Here is my code :-
1) MyFirebaseMessagingService.kt :-
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
showNotification(remoteMessage!!)
Log.e("fcm", "HElloo Call")
}
#SuppressLint("WrongConstant")
private fun showNotification(message: RemoteMessage) {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val i = Intent(this, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)
val androidChannel = NotificationChannel("1",
"sdccscsc", NotificationManager.IMPORTANCE_DEFAULT)
androidChannel.enableLights(true)
androidChannel.enableVibration(true)
androidChannel.lightColor = Color.GREEN
androidChannel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val builder = NotificationCompat.Builder(this, "1")
.setAutoCancel(true)
.setContentTitle(message.data["title"])
.setContentText(message.data["message"])
.setSmallIcon(R.drawable.main_logo)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pendingIntent)
manager.createNotificationChannel(androidChannel)
}
val i = Intent(this, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle(message.data["title"])
.setContentText(message.data["message"])
.setSmallIcon(R.drawable.main_logo)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pendingIntent)
manager.notify(0, builder.build())
}
Check your logcat if you are receiving the notification. IS your notification being displayed in the system tray?
There are two types of Message types
Notification message
FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages have a predefined set of user-visible keys and an optional data payload of custom key-value pairs.
Data message
Client app is responsible for processing data messages. Data messages have only custom key-value pairs.
as per my comment
You need to send notification data in Data messages
SAMPLE FORMAT
{
"message":{
"token":"your token",
"data":{
"key1" : "value1",
"key2" : "value2",
"key3" : "value4",
}
}
}
EDIT
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
Intent intent = new Intent(this, YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
intent.putExtra("ID",object.getString("data"));
} catch (JSONException e) {
e.printStackTrace();
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "Your_channel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("Description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorDarkBlue))
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage.getNotification().getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_MAX);
notificationManager.notify(1000, notificationBuilder.build());
notificationManager.cancelAll();

Categories

Resources